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-2026 CODEPRJ.COM