文件读写的意义

为什么需要文件读写?答:文件读写的目的是为了永久保存用户数据,否则程序一退出,数据就会消失。

C++方式

IO的含义

IO(input/output):指的是向设备输入数据和输出数据。

而IO设备有:文件、控制台、特定的数据类型stringstream。

C++中的IO流正是向这些IO设备写入数据(输出流、写文件),再从IO设备中读出数据(输入流、读文件)。是的,你没看错,这里是程序向设备输出设备对程序输入,一定要搞清楚对象。

C++利用文件流进行文件读写

其中涉及的类库有:ifstream(对文件进行读操作)、ofstream(对文件进行写操作)、fstream(对文件进行读、写操作)。

这些类库的头文件是:另外如遇报错,请使用命名空间 std。

就像是 string 类,即使你包含了头文件 ,可定义一个变量还是要加上 std::,除非你使用了命名空间 std 。

文本文件读写

文件打开的方式

fstream

模式标志描述
ios::in读方式打开文件
ios::out写方式打开文件
ios::trunc如果此文件已经存在,就会在打开文件之前,把文件长度截断为0
ios::app尾部追加方式(在尾部后进行写入)
ios::ate文件打开后,光标定位到文件尾
ios::binary二进制方式

如果选择多种模式可以用位操作符 | 连接 ,例如:

fstream ffile;ffile.open("test.txt",ios::in | ios::trunc) //以截断和读的方式打开文本文件

因为 fstream 类既能读又能写,我就讲 ifstream 和 ofstream 类。

#include #include using namespace std;//文本文件读写int main(void){//文件写ofstream out; //定义一个文件输出流对象string name;int age;out.open("test.txt"); //默认方式打开文件while (1){cout <> name;if (cin.eof()) //如果是文件结束符,退出循环{break;}out << name << " "; //姓名和空格写入文件cout <> age;out << age <> name;if (in.eof()) //读到文件结束符了{break;}cout << name <> age;if (in.eof()) {break;}cout << age << endl;}in.close();return 0;}

二进制文件读写

#include #include using namespace std;//二进制方式读写文件int main(void){//写二进制文件ofstream out;string name;int age;out.open("date.dat", ios::out | ios::binary);while (1){cout <> name;if (cin.eof()) //遇到文件结束符,也就是文件为空了{break;}out << name << '\t';cout <> age;if (cin.eof()){break;}//out << age <> name;if (in.eof()){break;}cout << name <> age ; //错误读取不了二进制文件,会一直死循环in.read((char*)&age, sizeof(age));cout << age << endl;}in.close();return 0;}

按指定格式读写文本文件

//指定格式读写文件#include #include #include #include  // stringstream类的头文件using namespace std;int main(void){//写string name;int age;ofstream outfile;outfile.open("test.txt");while (1){cout <> name;if (cin.eof()){break;}cout <> age;stringstream s;s << "姓名:" << name << "\t年龄:" << age << endl;//把指定格式的数据写入文件outfile << s.str(); //转成string 对象}outfile.close();//读ifstream infile;string line;char name2[32];infile.open("test.txt");while (1){getline(infile, line);//从文件中读取一行,保存在line中if (infile.eof()){break;}sscanf_s(line.c_str(), "姓名:%s 年龄:%d", name2, sizeof(name2), &age); //C语言的方式cout << "姓名:" << name2 << "年龄:" << age << endl;}infile.close();return 0;}