C++ 中文本的输入与输出fstream

头文件

<fstream> <ifstream> <ostream>


文本读取

1.实例化ifstream对象

2.和文本文件关联起来,用.open()

3.读取字符,用.get()或.getline()

4.判断输入是否成功,用eof()和fail()

5.关闭文件流,用close()


文本输入

扫描二维码关注公众号,回复: 1563005 查看本文章

1.实例化ofstream对象

2.和文本文件关联起来,用.open()

3.输入字符,用<<

4.关闭文件流,用close()


 
  
#include <iostream>
#include <fstream>

using namespace std;

//文本输入
int main()
{
	ofstream osf;
	osf.open("F:\\test.txt");

	osf << "First line ." << endl;
	osf << "Second line ." << endl;
	osf << "Third line ." << endl;
	osf << "Fourth line ." << endl;
	osf << "Fifth line ." << endl;

	osf.close();

	cout << "File created successfully ." << endl;

	system("pause");
	return 0;
}
//文本读取int main(){ifstream ifs;ifs.open("F:\\test.txt");//判断文件是否打开if (!ifs.is_open()){cout<<"Open failed !"<<endl;exit(EXIT_FAILURE);}char ch;//读取文本内容while (ifs.good()){ifs.get(ch);cout << ch;}//如果遇到文本结尾if (ifs.eof()){cout<<"It's an end ."<<endl;}ifs.close();system("pause"); return 0;}

猜你喜欢

转载自blog.csdn.net/weixin_42078760/article/details/80645403