C/C++ - 文件操作(一)
#include<iostream>
#include<string>
#include<cmath>
#include<cstdio> // FILE操作头文件。没有的话,CLION不会报错,直接显示自己设置的不能打开的语句,codeblocks会报错。
using namespace std;
const double PI=acos(-1.0);
int main()
{
FILE *fp=fopen("/Users/cih/Desktop/A.txt","r");
if(fp!=NULL)
{
int x;
fscanf(fp,"%d",&x);
cout<<x<<endl;
fclose(fp);
}
else
cout<<"Can't open it!"<<endl;
return 0;
}
// 用>和<做重定向
#include<iostream> #include<string.h> #include<fstream> // 需要包含该头文件 using namespace std; // ofstream 写 // ifstream 读 // fstream 读写 int main() { 写文件 ofstream ofs; // 创建流对象 ofs.open("路径 test.txt",打开方式); 打开方式:ios::in/out 读/写文件 ofs<<"写入的数据" ofs.close();// 关闭文件 读文件 ifstream ifs; ifs.open("test.txt",ios::in); if(!ifs.is_open()) // 判断文件是否打开成功 cout<<"Fail"<<endl; ifs.close(); 读数据方式1: char buf[110]= {0}; while(ifs>>buf) // 全部读完跳出while cout<<buf<<endl; ifs.close(); 读数据方式2: char buf[110]= {0}; while(ifs.getline(buf,110/sizeof(buf))) //char * ,最多读多少字节数 cout<<buf<<endl; 读数据方式3: string buf; while(getline(ifs,buf)) cout<<buf<<endl; ifs.close(); return 0; }
分类:
C++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」