C++文本文件输入输出操作详解与代码示例

慢慢来
慢慢来
发布时间:2026-10-16| 2人浏览过
原创

C++提供了强大的标准库来处理文件操作。通过将文件流对象与控制台输出入(cout/cin)进行类比,可以快速理解如何使用 ofstream 将数据写入磁盘文件,以及使用 ifstream 从文件中安全地读取数据。

文本文件输出:写入数据

要向文本文件中写入数据,需要引入 fstream 头文件并创建一个输出流对象。我们可以将其视为控制台中 cout 的“持久化”版本:

  • 核心类:在 fstream 头文件中定义的 std::ofstream 类专门用于处理输出。
  • 操作步骤:
    1. 声明对象:像定义普通变量一样创建 ofstream 实例。
    2. 关联文件:调用对象的 open() 方法,将对象绑定到具体的文件名上。
    3. 执行写入:使用流提取运算符 << 将数据类型写入文件。
    4. 释放资源:操作结束后务必调用 close() 方法,确保数据被保存到硬盘。
#include <fstream>
using namespace std;

// 示例:快速关联文件
ofstream OutFile;
OutFile.open("study.txt"); // 将对象与文件关联

以下是完整的写入示例。本程序首先获取用户输入,然后在屏幕显示,最后将相同的数据精确写入名为 information.txt 的文件中:

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

int main()
{
    char name[20];
    double height;
    double weight;

    // 1. 创建 ofstream 对象
    ofstream outFile;
    
    // 2. 与目标文件建立连接
    outFile.open("information.txt");
    
    cout << "Enter name: ";
    cin.getline(name, 20);
    
    cout << "Enter height: ";
    cin >> height;
    
    cout << "Enter weight: ";
    cin >> weight;

    // --- 控制台同步输出(仅展示效果) ---
    cout << fixed;
    cout.precision(2);
    cout.setf(ios_base::showpoint);
    cout << "Name: " << name << endl;
    cout << "Height: " << height << endl;
    cout << "Weight: " << weight << endl;

    // --- 文件写入操作 ---
    outFile << fixed;          // 设置小数为固定点格式
    outFile.precision(2);      // 保留两位小数
    outFile.setf(ios_base::showpoint); // 强制显示末尾的零
    outFile << "Name: " << name << endl;
    outFile << "Height: " << height << endl;
    outFile << "Weight: " << weight << endl;

    // 3. 必须关闭文件以保存数据
    outFile.close();
    return 0;
}

文本文件输入:读取数据

读取文件使用的是 std::ifstream 类。其逻辑与 cin 类似,但增加了状态检测的重要性,因为读取失败时如果不加判断会导致逻辑错误:

第1步:检查文件是否成功打开

在尝试读取之前,必须验证文件是否存在且已正常加载。如果尝试打开一个不存在的文件,后续的读取操作会产生错误的结果。可以使用 is_open() 方法进行拦截:

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

ifstream InFile;
InFile.open("information.txt");
if (!InFile.is_open()) {
    exit(EXIT_FAILURE); // 若未打开则终止程序
}

第2步:循环读取与状态判断

在处理数值或连续文本时,需配合 good() 来判断当前流是否可用,并通过 eof() 和 fail() 识别读取是正常结束还是因数据格式不匹配而中断:

// 循环直到达到文件末尾或遇到错误
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";

综合上述逻辑,以下是一个完整的读取实例。该程序接收用户输入的文件名,计算文件中所有 double 类型数值的总和与平均数,并对异常情况进行友好提示:

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

int main()
{
    char fileName[SIZE];
    ifstream InFile;
    
    cout << "Enter the name of data file: ";
    cin.getline(fileName, SIZE);
    
    cout << fileName << endl;
    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;
}

总结

通过上述对比可以看到,C++的文件I/O操作本质上是对流的封装。只要掌握了 ofstream 的写入流程和 ifstream 的安全校验机制,就能稳定地完成各种文本数据的存取任务。以上就是C++文本文件输入输出操作的详细内容,更多关于C++文件流编程的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。