Skip to content

[C++] 基本教學 05: 檔案讀寫

文字格式的資料可說是電腦系統最基礎的資料形式之一,比如說 Linux 作業系統,有許多的設定為了方便使用者能自由地調整,都以文字檔的格式儲存著。

在 C++ 中,若是要進行文字檔案的讀寫,則需要透過 fstream 所提供的 ifstream(輸入)、ofstream(輸出)來處理;也可以使用 fstream 指定不同的 open() 模式來讀寫。

我們可以透過 open() 函式來讀取指定的文字檔案,其模式有許多種類:

ModeUsage
ios::in檔案讀取模式
ios::out檔案寫入模式
ios::ate從檔案結尾讀取及寫入資料
ios::app從檔案結尾寫入資料
ios::trunc清除檔案內容
ios::nocreat若開啟不存在的檔案時,則報錯
ios::noreplace若開啟存在的檔案時,ate、app 被設定,則報錯
ios::binary以二進制模式讀取檔案
http://www.cplusplus.com/doc/tutorial/files/

以下就直接以程式示範如何寫入、讀取檔案。


讀寫檔案

建立新的文字檔

以下是個簡單的範例檔案,建立了名為 test.txt 的新的文字檔案,並寫入了 “Today is a nice day.” 這行字。

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


int main() {
    // Create a new file
    ofstream newFile;
    newFile.open("test.txt");

    // Write to the file
    newFile << "Today is a nice day.";
    newFile.close();

    return 0;
}


or

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


int main() {
    // Create a new file
    fstream newFile;
    newFile.open("test.txt", ios::out | ios::trunc);

    // Write to the file
    newFile << "Today is a nice day.";
    newFile.close();

    return 0;
}




寫入現有文字檔

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


int main() {
    // Open file
    fstream myFile;
    myFile.open("test.txt", ios::app);

    // Write to the file
    myFile << "\nI want to go to play.";

    // Close file
    myFile.close();

    return 0;
}




讀取檔案

若要讀取剛才所建立的 test.txt,則可以使用以下的程式:

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


int main() {
    // Settings
    string line;

    // Open file
    ifstream myFile;
    myFile.open("test.txt");

    // Print file content
    while (getline(myFile, line)) {
        cout << line << endl;
    }

    // Close file
    myFile.close();

    return 0;
}



Output:

Today is a nice day.
I want to go to play.

References


Read More

Tags:

Leave a Reply