一、常用文件打开方式
二、读写文件步骤(文本文件)
1、写文件步骤
1)#include <fstream> //
2)ofstream ofs; //创建流对象
3)ofs.open("文件路径",打开方式); //打开文件
4)ofs << "写入的数据"; //写数据
1 #include<iostream> 2 #include<fstream> 3 using namespace std; 4 5 void test() 6 { 7 //ofstream ofs("test.txt",ios::out); //创建流对象,并创建文件和打开方式 8 ofstream ofs; //创建流对象 9 ofs.open("test.txt", ios::out); //创建文件和打开方式 10 ofs << "姓名:码子" << endl; 11 ofs << "年龄:18" << endl; 12 ofs.close(); //关闭文件 13 } 14 15 int main() 16 { 17 test(); 18 19 return 0; 20 }
View Code
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 using namespace std; 5 6 void test() 7 { 8 ifstream ifs; 9 ifs.open("test.txt", ios::in); 10 //判断是否打开文件 11 if (!ifs.is_open()) 12 { 13 cout << "打开文件失败" << endl; 14 } 15 //第一种读取方式 16 /*char buf[1024] = ""; 17 while (ifs>>buf) 18 { 19 cout << buf << endl; 20 }*/ 21 22 //第二种读取方式 23 /*char buf[1024] = ""; 24 while (ifs.getline(buf,sizeof(buf))) 25 { 26 cout << buf << endl; 27 }*/ 28 29 //第三种读取方式 30 string buf = ""; 31 while (getline(ifs, buf)) 32 { 33 cout << buf << endl; 34 } 35 36 //第四种读取方式,不推荐 37 /* char c; 38 while ((c = ifs.get()) != EOF) 39 { 40 cout << c; 41 }*/ 42 43 ifs.close(); 44 } 45 46 int main() 47 { 48 test(); 49 50 return 0; 51 }
View Code
三、读写文件步骤(二进制文件)
1、写文件步骤
和文本文件类似,不在累赘。
2、写文件代码(二进制)
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 using namespace std; 5 6 class Cat 7 { 8 public: 9 Cat(const char name[] = "", int age = 0,const char color[]="") 10 { 11 strcpy_s(m_Name, name); 12 strcpy_s(m_Color,color); 13 m_Age = age; 14 } 15 char m_Name[32]; 16 char m_Color[32]; 17 int m_Age; 18 }; 19 20 void test1() 21 { 22 Cat c("老黄",2,"Yellow"); 23 ofstream ofs("Cat.txt", ios::out | ios::binary); //创建流对象,并设置打开文件方式 24 ofs.write((const char*)&c, sizeof(c)); //写入文件 25 ofs.close(); //关闭文件 26 } 27 28 int main() 29 { 30 test1(); 31 return 0; 32 }
View Code
3、读文件步骤
省略
4、读文件代码(二进制)
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 using namespace std; 5 6 class Cat 7 { 8 public: 9 Cat(const char name[] = "", int age = 0,const char color[]="") 10 { 11 strcpy_s(m_Name, name); 12 strcpy_s(m_Color,color); 13 m_Age = age; 14 } 15 char m_Name[32]; 16 char m_Color[32]; 17 int m_Age; 18 }; 19 20 21 void test2() 22 { 23 Cat c; 24 ifstream ifs("Cat.txt", ios::in | ios::binary); //创建流对象,并设置打开文件方式 25 //验证是否成功打开文件 26 if (!ifs.is_open()) 27 { 28 cout << "文件打开失败" << endl; 29 } 30 ifs.read((char*)&c, sizeof(c)); //读出文件 31 cout << "名字: " << c.m_Name << endl; 32 cout << "颜色: " << c.m_Color << endl; 33 cout << "年龄: " << c.m_Age << endl; 34 ifs.close(); //关闭文件 35 } 36 37 int main() 38 { 39 test2(); 40 return 0; 41 }
View Code
原文链接: https://www.cnblogs.com/GEEK-ZHAO/p/12313507.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/329990
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!