使用C++ ifstream讀取文件內容的方法

一、打開文件

C++的ifstream可用於讀取文件內容,首先需要打開文件。

使用ifstream對象的open()函數打開文件,如果文件不存在,則會創建該文件,如果文件存在,則會打開該文件,同時覆蓋文件原有內容。

#include 
#include 
using namespace std;

int main()
{
    string filename = "example.txt";
    ifstream ifs;
    ifs.open(filename);

    if(!ifs.is_open())
    {
        cout << "打開文件失敗" << endl;
        return 0;
    }

    // 文件讀取代碼

    ifs.close();
    return 0;
}

在打開文件之後,需要使用流提取運算符「>>」讀取文件中的內容。

二、讀取文件內容

使用流提取運算符「>>」讀取文件中的內容,每次讀取一行。

#include 
#include 
using namespace std;

int main()
{
    string filename = "example.txt";
    ifstream ifs;
    ifs.open(filename);

    if(!ifs.is_open())
    {
        cout << "打開文件失敗" << endl;
        return 0;
    }

    string line;
    while(getline(ifs,line))
    {
        cout << line << endl;
    }

    ifs.close();
    return 0;
}

使用getline()函數讀取文件中的一行,當讀到文件結尾或者讀取錯誤時,getline()函數返回false,循環結束。

三、讀取文件中的數字

使用流提取運算符「>>」比較簡單,但讀取文件中的數字需要注意,需要使用C++提供的字元串轉數字函數stoi()。

#include 
#include 
using namespace std;

int main()
{
    string filename = "example.txt";
    ifstream ifs;
    ifs.open(filename);

    if(!ifs.is_open())
    {
        cout << "打開文件失敗" << endl;
        return 0;
    }

    string line;
    while(getline(ifs,line))
    {
        int num = stoi(line);
        cout << num << endl;
    }

    ifs.close();
    return 0;
}

四、逐個字元讀取文件內容

可以使用流提取運算符「>>」逐個讀取文件中的字元。

#include 
#include 
using namespace std;

int main()
{
    string filename = "example.txt";
    ifstream ifs;
    ifs.open(filename);

    if(!ifs.is_open())
    {
        cout << "打開文件失敗" <> c)
    {
        cout << c;
    }

    ifs.close();
    return 0;
}

這段代碼會將文件中的每個字元都讀取並輸出,但只能讀取文本文件,不能讀取二進位文件。

五、二進位文件的讀取

對於二進位文件的讀取,可以使用read()函數從流中讀取一定數量的位元組。

#include 
#include 
using namespace std;

int main()
{
    string filename = "example.bin";
    ifstream ifs;
    ifs.open(filename, ios::binary | ios::in);

    if(!ifs.is_open())
    {
        cout << "打開文件失敗" << endl;
        return 0;
    }

    char data[100];
    ifs.read(data, 100);

    ifs.close();
    return 0;
}

ios::binary標誌表示打開文件為二進位文件。

六、總結

使用C++的ifstream可以簡單地讀取一個文件的內容,可以按行讀取、逐個字元讀取、讀取二進位文件等。需要注意的是,不同類型的文件需要不同的讀取方式。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/249190.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 13:32
下一篇 2024-12-12 13:32

相關推薦

發表回復

登錄後才能評論