c++ 文件存取

一、將數據寫入文件

void writeToFile()
{
	std::ofstream outfile;
	outfile.open("data.txt"); //創建、打開文件

	for(unsigned int x = 0; x < N; x++)
	{
		for(unsigned int y = 0; y < M; y++)
		{
			outfile<<data[x * N + y]<<" "; //寫入數據
		}
		outfile<<std::endl;
	}
	outfile.close(); //關閉文件
		
}


二、從文件中讀取數據

void readFormFile()
{
	fstream in;
	in.open("data.txt"); //打開文件
	//逐字符讀取
	char c;
	while(!in.eof())
	{
		in>>c;//讀取字符

		//其他操作
	}

	//逐行讀取
	string str;
	while(getline(in,str))
	{
		//其他操作
	}

	in.close();//關閉文件
}


ps:

頭文件#include <fstream>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章