C++中文件读写的操作


在C++中读读写文件一般指的就是磁盘中的文本文件和二进制文件:

文本文件:以字符序列组成的文件

二进制文件:由二进制组成的文件

读写文件采用ofstream和ifstream文件流,两者可用头文件<fstream>包含,具体代码如下:

#include <iostream>
#include <vector>
#include <fstream>
using namespace std;


int main()
{
	ofstream out;//输出文件
	out.open("D:\\PPC\\test.txt");
	if (out.is_open())
	{
		out << "This is a line.\n";
		out << "This is another line.\n";
		out.close();
	}
	char buffer[256];
	ifstream in("D:\\PPC\\test.txt");//读文件
	if (!in.is_open())
	{
		cout << "error!";
		getchar();//让dos停留观测结果用,可删除
		exit(1);
	}
	while (!in.eof())
	{
		in.getline(buffer, 100);
		cout << buffer << endl;
	}
	getchar();
	return 0;
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM