C++学习笔记:对文件流的写入和读取

前言

c++对文件的读取写入,最简单的是利用下面三个类。

名称 描述
ofstream Stream class to write on files
ifstream Stream class to read from files
fstream Stream class to both read and write from/to files.

ofstream建立和写入文件

建立一个名为 test.txt 的文档,写入数据的方式多种。

#include<iostream>
#include<fstream>

using namespace std;

int main() {

	ofstream ofs("test.txt");
	if ( !ofs.is_open() ) {
		cout << "failed" << endl;
		return 0;
	}

	ofs << "hello world!" << endl;  //直接写入

	int a = 10086;
	ofs << a << endl;  //间接写入

	string s = "welcome!";
	ofs << s.c_str() << "\t" << a << endl;    //不同格式混合写入

	string ss = "this is a test for ofstream!\n";
	ofs.write(ss.c_str() , ss.length());      //利用write方法

	ofs.close();


	system("pause");
}

ifstream读取文件

从 test.txt 文档中读取数据,可以使用不同的数据类型来读取,过程都大同小异。

#include<iostream>
#include<fstream>
#include<sstream>

using namespace std;

int main() {

	ifstream ifs;
	ifs.open("test.txt" , ios::in);
	if ( !ifs ) {
		cout << "no such file" << endl;
		return 0;
	}

	cout << "\n**********stringbuf**********\n" << endl;
	string str;
	stringbuf *sb = new stringbuf();
	while ( !ifs.eof() ) {
		ifs >> sb;
		cout << sb;
		str.append(sb->str());
	}
	cout << "\n**********stringbuf to string**********\n" << endl;
	cout << str;
	cout << "\n**********char**********\n" << endl;
	ifs.seekg(0 , ifs.beg); //当前坐标要归零
	char cc;
	while ( !ifs.eof() ) {
		ifs.get(cc);
		cout << cc;
	}
	ifs.close();

	system("pause");
}

最后结果

在这里插入图片描述

fstream对文件读写操作

fstream可以说是上面两个的综合,不过个人建议,还是用上面两个类,编程的时候便于区分。

#include<iostream>
#include<fstream>

using namespace std;

int main() {

	fstream fs("test2.txt" , ios::out); //创建文件
	if ( !fs.is_open() ) {
		cout << "failed" << endl;
		return 0;
	}

	fs << "test2" << endl; //写入数据
	fs.close();

	fs.open("test2.txt" , ios::in); //读取文件
	if ( !fs.is_open() ) {
		cout << "no such file" << endl;
		return 0;
	}

	char c;
	while ( !fs.eof() ) {
		fs.get(c);
		cout << c;
	}

	fs.close();
	
	system("pause");
}
发布了45 篇原创文章 · 获赞 46 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/founderznd/article/details/51847914