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

C++通过fstream头文件提供ifstream、ofstream和fstream类进行文件操作;2. 写入文件使用ofstream,示例中向data.txt写入数据并检查文件是否成功打开。

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

包含必要的头文件

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

  • #include —— 提供文件流支持
  • #include iostream> —— 用于输入输出显示
  • #include —— 如果需要读取字符串内容

写入文本文件(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") 创建一个输出流并打开文件
  • is_open() 检查文件是否成功打开
  • 操作符写入内容,与cout用法一致
  • close()关闭文件是良好习惯

如需追加内容,可使用:

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;
}

说明:

  • getline(inFile, line) 每次读取一行,保留空格
  • inFile >> word,则以空白字符分割,无法读取完整含空格的行

同时读写文件(fstream)

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

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

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

常用模式组合:

  • ios::in —— 读取
  • ios::out —— 写入(默认覆盖)
  • ios::app —— 追加
  • ios::ate —— 打开后定位到文件末尾

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