1. 程式人生 > 其它 >C++學習筆記(二)——寫入文字到檔案/從檔案中讀取文字

C++學習筆記(二)——寫入文字到檔案/從檔案中讀取文字

寫入文字到檔案

源程式:C++Primer例題6.15 將輸入的三個不同型別的變數寫入檔案中儲存。

#include<iostream>
#include<fstream>

using namespace std;

int main()//寫入文字到檔案
{
char automobile[50];
int year;
double a_price;
double d_price;

ofstream outFile;
outFile.open("carinfo.txt");

cout << "Enter the make and model of automobile:";
cin.getline(automobile,50);
cout << "Enter the model year:";
cin >> year;
cout << "Enter the original asking price:";
cin >> a_price;
d_price = 0.913*a_price;

cout << fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout << "Make and model:" << automobile << endl;
cout << "Year:" << year << endl;
cout << "Was asking $" << a_price << endl;
cout << "Now asking $" << d_price << endl;

outFile << fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
outFile << "Make and model:" << automobile << endl;
outFile << "Year:" << year << endl;
outFile << "Was asking $" << a_price << endl;
outFile << "Now asking $" << d_price << endl;

outFile.close();
}

一、標頭檔案

#include<iostream>
#include<fstream>

iostream:在此標頭檔案中,定義了用來處理輸出的類:ostream類。它還聲明瞭一個名為cout的ostream變數。必須指明名稱空間std;宣告名稱空間必須使用編譯指令using或者字首std::。

fstream:定義了一個用於處理輸出的ofstream類,輸出檔案時必須宣告一個或多個ofstream變數,並對其命名,命名時需遵守常用的命名規則。使用完檔案後,應使用close()方法將檔案關閉。

例:宣告物件:

    ofstream outFile;

    ofstream fout;

  將物件與檔案關聯:

    outFile.open("fish.txt");

    char filename[50];

    cin >> filename;

    fout.open(filename);

總之,使用檔案輸出的主要步驟:

1. 包含標頭檔案fstream。

2. 建立一個ofstream物件。

3. 將該ofstream物件同一個檔案關聯起來。

4. 就像使用cout那樣使用該ofstream物件。

二、 存疑語句

cout << fixed;//表示用一般的方式輸出浮點數

cout.precision(2);//是輸出流cout的一個格式控制函式,也就是在iostream中的一個成員函式。precision()返回當前的浮點數的精度值,而cout.precision(val)其實就是在輸出的時候設定輸出值以新的浮點數精度值顯示,即小數點後保留val位。

參考:https://blog.csdn.net/huangchijun11/article/details/72934222

cout.setf(ios_base::showpoint);//顯示浮點數小數點後面的零。

這三條語句都是格式控制語句。

另,開啟檔案時,使用的語句為:outFile.open("carinfo.txt");

當檔案"carinfo.txt"不存在時,執行此語句,將建立一個檔案。但如果檔案"carinfo.txt"已存在,那麼預設情況下,open()將先截斷該檔案,將其長度截斷到0——即丟棄原有內容,然後將新的內容輸入到檔案中。後續將學習如何將新的輸出加入到該檔案中。

如果"carinfo.txt"存在,但禁止訪問,將無法輸入。

從檔案中讀取文字

源程式:是一個統計分數的程式,待讀取的檔案中儲存的是三行有浮點數有整數的數。

#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
const int SIZE = 60;

int main()
{
char filename[SIZE];
ifstream inFile;

cout << "Enter name of data file:";
cin.getline(filename,SIZE);
inFile.open(filename);
if(!inFile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;

inFile >> value;
while(inFile.good())
{
++count;
sum += value;
inFile >> value;
}
if(inFile.eof())
{
cout << "End of file reached.\n";
}
else if(inFile.fail())
{
cout << "Input terminated by data mismatch.\n";
}
else
{
cout << "Input terminated for unknown reason.\n";
}
if(count == 0)
{
cout << "No data processed.\n";
}
else
{
cout << "Items read:" << count << endl;
cout << "Sum:" << sum << endl;
cout << "Average:" << sum/count << endl;
}
inFile.close();

return 0;
}

一、標頭檔案

#include<iostream>
#include<fstream>
#include<cstdlib>

前兩個不多解釋,#include<cstdlib>:是一些常用的函式,但是又不知道把它們放到哪裡合適,因此就都放到了stdlib.h這個標頭檔案中。stdlib.h可以提供一些函式與符號常量。

參考:https://blog.csdn.net/Iaired/article/details/78700180

二、存疑語句

ifstream inFile;//如ofstream 用來宣告一個物件

inFile.is_open();//作用是檢查檔案是否被成功開啟,如果成功開啟,返回true。

參考:https://blog.csdn.net/guotianqing/article/details/107138117

exit(EXIT_FAILURE);

exit()函式定義於cstdlib標頭檔案中,它定義了兩個變數:

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

exit(0): 正常執行程式並退出程式。

exit(1): 非正常執行導致退出程式。

故:

exit(EXIT_SUCCESS) : 代表安全退出。

exit(EXIT_FAILURE) : 代表異常退出。

參考:https://segmentfault.com/q/1010000009537479

這條語句的作用即為:

1.與具有執行緒儲存持續時間的當前執行緒關聯的物件被銷燬(僅限 C++11)。

2. 具有靜態儲存持續時間的物件被銷燬(C++)並呼叫在 atexit 註冊的函式。

3. 所有 C 流(使用 <cstdio> 中的函式開啟)都被關閉(如果緩衝,則重新整理),並且所有使用 tmpfile 建立的檔案都被刪除。控制權返回到主機環境。

inFile >> value;//讀取下一個值,參考我的C++學習筆記(一),有詳細寫C++如何處理輸入行

inFile.good();//good()方法指出讀取輸入的最後一次操作是否成功。

inFile.eof();//判斷檔案長度是否到達eof

inFile.fail();//fail()來判斷當前的輸入的型別和預期的是否相同,如不同fail()返回true。

當輸入流讀取失敗時,會將字元放在原處,等待下次讀取!

此外,fail()返回了true之後要用clear()來清除fail狀態。

三、補缺

EOF:是end of file的縮寫,表示"文字流"(stream)的結尾。這裡的"文字流",可以是檔案(file),也可以是標準輸入(stdin)。

EOF不是特殊字元,而是一個定義在標頭檔案stdio.h的常量,一般等於-1。

#define EOF (-1)

詳細參考:https://zhidao.baidu.com/question/584929047.html