C++ I/O文件读写操作的示例代码

2020-06-10 12:00:40于丽

IO: 向设备输入数据和输出数据C++的IO流


c++中,必须通过特定的已经定义好的类, 来处理IO(输入输出)


文件流: 对文件进行读写操作
头文件:
类库:
ifstream 对文件输入(读文件)
ofstream 对文件输出(写文件)
fstream 对文件输入或输出

//写文件

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string name;
	int age;
	ofstream outfile; //也可以使用fstream, 但是fstream的默认打开方式不截断文件长度

	// ofstream的默认打开方式是, 截断式写入 ios::out | ios::trunc
	// fstream的默认打开方式是, 截断式写入  ios::out
	// 建议指定打开方式
	outfile.open("user.txt", ios::out | ios::trunc);

	while (1) {
		cout << "请输入姓名: [ctrl+z退出] ";
		cin >> name;
		if (cin.eof()) { //判断文件是否结束
			break;
		}
		outfile << name << "t";

		cout << "请输入年龄: ";
		cin >> age; 
		outfile << age << endl; //文本文件写入
	}

	// 关闭打开的文件
	outfile.close();

	system("pause");
	return 0;
}

//读文件

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string name;
	int age;
	ifstream infile;
	infile.open("user.txt");

	while (1) {
		infile >> name;
		if (infile.eof()) { //判断文件是否结束
			break;
		}
		cout << name << "t";

		infile >> age;
		cout << age << endl; 
	}

	// 关闭打开的文件
	infile.close();

	system("pause");
	return 0;
}

对二进制文件流读写

文本文件和二进制文件的区别?

文本文件: 写数字1, 实际写入的是 ‘1'
二进制文件:写数字1, 实际写入的是 整数1(4个字节,最低字节是1, 高3个字节都是0)
写字符‘R'实际输入的还是‘R'
写二进制文件
使用文件流对象的write方法写入二进制数据.

//写二进制文件

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string name;
	int age;
	ofstream outfile;
	outfile.open("user.dat", ios::out | ios::trunc | ios::binary);

	while (1) {
		cout << "请输入姓名: [ctrl+z退出] ";
		cin >> name;
		if (cin.eof()) { //判断文件是否结束
			break;
		}
		outfile << name << "t";

		cout << "请输入年龄: ";
		cin >> age; 
		//outfile << age << endl; //会自动转成文本方式写入
		outfile.write((char*)&age, sizeof(age));
	}

	// 关闭打开的文件
	outfile.close();

	system("pause");
	return 0;
}