通八洲科技

c++如何读取和写入文本文件_c++文件I/O操作与文本文件读写方法

日期:2025-11-09 00:00 / 作者:穿越時空
C++通过fstream头文件提供ifstream、ofstream和fstream类进行文件操作;2. 写入文件使用ofstream,示例中向data.txt写入数据并检查文件是否成功打开。

在C++中进行文本文件的读取和写入,主要依赖于标准库中的fstream头文件,它提供了三个核心类:ifstream(用于读取文件)、ofstream(用于写入文件)和fstream(可同时读写)。这些类基于流的概念,使用起来直观且灵活。

包含必要的头文件

要进行文件操作,必须包含以下头文件:

写入文本文件(ofstream)

使用ofstream可以轻松将数据写入文本文件。默认情况下,写入会覆盖原文件内容;若需追加,可指定模式。

示例:写入数据到data.txt

#include 
#include 
using namespace std;

int main() {
    ofstream outFile("data.txt");
    if (outFile.is_open()) {
        outFile << "Hello, World!" << endl;
        outFile << "This is a test." << endl;
        outFile.close();
        cout << "数据已写入文件。" << endl;
    } else {
        cout << "无法打开文件进行写入。" << endl;
    }
    return 0;
}

说明:

如需追加内容,可使用:

ofstream outFile("data.txt", ios::app);

读取文本文件(ifstream)

使用ifstream从文本文件中读取内容。可以按行、按词或整个文件读取。

示例:逐行读取data.txt

#include 
#include 
#include 
using namespace std;

int main() {
    ifstream inFile("data.txt");
    string line;
    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "无法打开文件进行读取。" << endl;
    }
    return 0;
}

说明:

同时读写文件(fstream)

当需要对同一文件进行读写操作时,可使用fstream,并指定打开模式。

示例:以读写方式打开文件

fstream file("data.txt", ios::in | ios::out);

常用模式组合:

基本上就这些。掌握ifstreamofstreamfstream的基本用法,就能处理大多数文本文件读写需求。关键注意检查文件是否成功打开,并选择合适的读取方式。不复杂但容易忽略细节。