C++的IO

C++提供三种标准的IO(输入输出)

1.从标准设备IO(显示器,键盘之类的)

2.从文件进行IO

3.从存储变量进行(stringstream/istringstream/ostringstream)

首先我们先来看看C++提供的IO类的继承关系图(本人画图不好,懂那个意思就行了)

来看看流的概念(其实就把它当成一种管道(水管之类的))

我们直接从文件IO开始把

// 文件流: 对文件进行读写操作

头文件:  <fstream>

类库:

   ifstream    对文件输入(读文件)

   ofstream    对文件输出(写文件)

   fstream     对文件输入或输出

// 文件的打开方式(我直接从我的文档截图了)

代码的话,我给一些事例,参考一下简单的用法。

// 1.普通的把数据写入文件

	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();

 2. 把数据以二进制形式写入文件

我们先来讨论二进制IO和普通的文本IO有什么区别把:

相同点:两种形式IO的内容是字母,例:写 A,实际上输入还是 字符 ‘A’

不同点:普通文本写数字 1 其实输入字符 ‘1’,但二进制就不同了,你写的数字是 1 但它输入的 整数1(4个字节,最低字节是1, 高3个字节都是0)

总结就是  两者在  数字的IO 是不同的

// 以二进制的形式把数据写入文件
	ofstream outfile;
	string name;
	int age;
again:
	outfile.open("binary.txt", ios_base::out | ios_base::binary | ios_base::trunc);
	if (!outfile.is_open()) {
		cerr << "open file err, try to open again!" << endl;
		goto again;
	}
	while (1) {
		cout << "please input the name:";
		cin >> name;

		if (cin.eof()) break;

		cout << "please input the age:";
		cin >> age;
		// outfile << name << '\t' << age << endl; // 这种读取方式 还是以字符形式来读取的
		outfile << name << "\t";
		outfile.write((const char*)& age, sizeof(age));
	}
	outfile.close();
	// 以二进制文件的形式从文件读 数据
	ifstream infile;
again_1:
	infile.open("binary.txt", ios_base::in | ios_base::binary);
	if (!infile.is_open()) {
		cerr << "open file err, try to open again!" << endl;
		goto again_1;
	}
	string buf;
	int age_buf = 0;
	char isempty;
	while (1){
		// infile.read(buf, sizeof(buf)).read(&isempty, sizeof(isempty)).read((char *)&age_buf, sizeof(age_buf));
		// infile >> name >> age_buf;
		infile >> buf;// read the txt in txt
		if (infile.eof()) break;
		infile.read(&isempty, sizeof(char)); // read the '\t'
		infile.read((char*)& age_buf, sizeof(age_buf)); // read the number in binary

		cout << buf << '\t' << age_buf << endl;
	}
	infile.close();

 这里一定要注意从二进制文件的 读数据的时候 ,极容易发生错误。

代码太多了 我就不写了然这个博客就很长,让人没有读下去的欲望了, 谢谢大家。

 

猜你喜欢

转载自blog.csdn.net/qq_44065088/article/details/103031586