【C++】如何進行簡單的檔案輸入、輸出?(基本操作及程式碼示例)(程式設計習慣)
阿新 • • 發佈:2018-12-16
使用cin進行輸入時,程式將輸入 視為一系列的位元組,每個位元組都被解釋為字元編碼,輸入一開始都是字元資料。
輸出檔案開啟
//第一種
ofstream outFile;
outFile.open("my.txt");
//第二種
ofstream fout;
char filename[50];
cin >> filename;
fout.open(filename);
//最後都需要關閉檔案
outFile.close();
fout.close();
cout輸出的常用屬性設定
cout << fixed; //使用小數計數法
cout.precision(2); //輸出精度
cout.sef( ios_base::showpoint ); //輸出小數點後面的0
讀取文字檔案
//第一種 ifstream inFile; inFile.open("hello.txt"); //第二種 ifstream fin; char filename[50]; cin >> filename; fin.open(filename); //同樣都要關閉 inFile.close(); fin.close();
判斷檔案是否開啟成功
inFile.open("hello.txt");
if(!inFile.is_open())
{
exit(EXIT_FAILURE)
}
檔案終止的真正原因判斷
if (inFile.eof())
cout <<"正常結束" <<endl;
else if(inFile.fail())
cout << "型別不匹配" <<endl;
else
cout << "檔案故障,未知原因"<<endl;