营销网站建设企划案例域名权重
文件操作
- 所有数据程序运行结束后都会释放
- 通过文件可以将数据持久化
- 头文件
- 文件类型分为两种
- 文本文件—文件以文本的ASCII码形式存储在计算机中
- 二进制文件—文件以文本的二进制存储在计算机中
- 操作文件的三大类
- ofstream—写操作
- ifstream—读操作
- fstream—读写操作
- 文本文件
- 写文件
- 包含头文件
- #include
- 创建流对象
- ofstream ofs;
- 打开文件
- ofs.open(“文件路径”,打开方式);
- 写数据
- ofs << “写入数据”
- 关闭文件
- ofs.close();
- 注意
- 打开方式—需要时查找
- 文件打开方式可以配合使用,利用|操作符
- 用二进制方式写文件—ios::binary|ios::out
#include<iostream>#include<fstream>using namespace std;void test(void){ofstream ofs;ofs.open("test.txt",ios::out);ofs<<"name"<<endl;ofs<<"test end"<<endl;ofs.close();}int main(){test();return 0;}
- 包含头文件
- 读文件
- 包含头文件
- #include
- 创建流对象
- ifstream ifs;
- 打开文件
- ifs.open(“文件路径”,打开方式);
- 读数据
- 四种读取方式
- 关闭文件
- ifs.close();
#include<iostream>#include<fstream>using namespace std;void test(void){ifstream ifs;ifs.open("test.txt",ios::in);if(!ifs.is_open()){cout << "打开失败" << endl;return ; }// //第一种读// char buf[1024] = {0};// while (ifs >> buf)// {// cout << buf << endl;// }// // 第二种// char buf[1024] = {0};// while (ifs.getline(buf, sizeof(buf)))// {// cout << buf << endl;// }// 第三种#include<string>string buf;while(getline(ifs,buf)){cout << buf << endl;}// // 第四种// char c;// while ((c=ifs.get())!=EOF)//EOF文件结尾// {// cout << c;// }ifs.close();}int main(){test();return 0;}
- 写文件
- 二进制文件
- 打开方式要指定为ios::binary
- 写文件
- 二进制方式写文件主要利用流对象调用成员函数write
- 函数原型:ostream& write(const char* buffer, int len);
- 参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
- 读文件
- 二进制方式读文件主要利用流对象调用成员函数read
- 函数原型:istream& read(char *buffer, int len);
- 参数解释:字符指针buffer指向内存中一段存储空间,len是读写的字节数
#include<iostream>#include<fstream>using namespace std;class Person{public:Person(char* name, int age){m_name = name;m_age = age;} char *m_name;int m_age;};void testw(void){ofstream ofs;ofs.open("person.txt", ios::out|ios::binary);Person p("zhangsan", 10);ofs.write((const char *) &p, sizeof(Person));ofs.close();}void testr(void){ifstream ifs;ifs.open("person.txt", ios::in|ios::binary);if(!ifs.is_open()){cout<<"file open fail";}else{Person p("no", 0);ifs.read((char* )&p, sizeof(Person));cout << "name " << p.m_name << " age " << p.m_age << endl;}ifs.close();}int main(){testw();testr();return 0;}