C++实现常用的文件操作
①输出到文本文件(txt)
1 #include<iostream> 2 #include<fstream> 3 using namespace std; 4 int main() { 5 ofstream doc("test.txt", ios::app); 6 //ios::app如果没有该文件,生成空文件; 7 //如果有文件,在文件尾追加 8 //如果打开失败 9 if (doc.fail()) { 10 cout << "error" << endl; 11 return 1; 12 } 13 int temp; 14 cin>>temp; 15 doc<<temp;//输出到文件中 16 doc.close();//关闭输出流 17 return 0; 18 }
②从文本文件读入数据
#include<iostream> #include<fstream> using namespace std; int main() { ifstream doc("test.txt"); int t,sum=0; if (doc.fail()) { cout << "error "<< endl; } while (doc >> t) {//从文件中读入一个整型数据且不为空 sum += t; cout << t << endl;//输出这个读取到的数值 } cout<<endl<<sum<<endl; doc.close(); return 0; }
③二进制写文件
1 #include<iostream> 2 #include<fstream> 3 using namespace std; 4 int main() { 5 ofstream doc("bfile1.dat",ios::out | ios::app | ios::binary); 6 if (doc.fail()) {//当文件打开失败时 7 cout << "error" << endl; 8 } 9 float t[] = {1.234,4242.212,4242,314.53,890.2}; 10 int count = 0; 11 while (count < 5) { 12 doc.write((char *)&(t[count++]), sizeof(float)); 13 } 14 doc.close(); 15 return 0; 16 }
④二进制读文件
1 #include<iostream> 2 #include<fstream> 3 using namespace std; 4 int main() { 5 ifstream doc("bfile1.dat", ios::in | ios::binary); 6 if (doc.fail()) { 7 cout << "error" << endl; 8 } 9 float t; 10 while (doc.read((char *)&t, sizeof(float))) { 11 sum += t; 12 cout << t << ends; 13 } 14 cout << endl << sum << endl; 15 doc.close(); 16 }
⑤二进制读写自定义类
1 #include<iostream> 2 #include<fstream> 3 using namespace std; 4 class employee { 5 private: 6 int num; 7 char name[20]; 8 int age; 9 public: 10 void input(int num1, char * name1, int age1) { 11 strcpy_s(name, name1); 12 num = num1; 13 age = age1; 14 } 15 void show() { 16 cout << num << ends<<name<<ends<<age<<endl; 17 } 18 }; 19 int main() { 20 employee e1, e2; 21 ofstream os("class.dat",ios::app|ios::binary|ios::out);//输出流 22 e1.input(12345, (char*)"小明", 19); 23 os.write((char*)(&e1) ,sizeof(e1)); 24 os.close(); 25 26 ifstream is("class.dat", ios::binary | ios::in);//输入流 27 is.read((char*)(&e2), sizeof(e2)); 28 e2.show(); 29 is.close(); 30 }
"你的指尖,拥有改变世界的力量! "
欢迎关注我的个人博客:https://sugarat.top
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧