C++ 文件读写基础

C++ 通过 <fstream> 库提供文件操作功能,主要包含 ifstream(输入文件流)、ofstream(输出文件流)和 fstream(双向文件流)三类。

写入文件(ofstream)

创建 ofstream 对象并打开文件,通过 << 运算符或 write() 方法写入内容。写入完成后需关闭文件。

#include <fstream>
#include <string>

std::ofstream outFile("example.txt");
if (outFile.is_open()) {
    outFile << "Hello, World!\n";
    outFile << 42 << "\n";
    outFile.close();
} else {
    std::cerr << "Failed to open file\n";
}

读取文件(ifstream)

使用 ifstream 打开文件,通过 >> 运算符或 getline() 逐行读取内容。

#include <fstream>
#include <string>
#include <iostream>

std::ifstream inFile("example.txt");
std::string line;
if (inFile.is_open()) {
    while (std::getline(inFile, line)) {
        std::cout << line << "\n";
    }
    inFile.close();
} else {
    std::cerr << "Failed to open file\n";
}


二进制文件操作

二进制读写使用 read()write() 方法,需指定数据指针和字节长度。

写入二进制数据
struct Data {
    int id;
    double value;
};

Data data = {1, 3.14};
std::ofstream binOut("data.bin", std::ios::binary);
if (binOut) {
    binOut.write(reinterpret_cast<char*>(&data), sizeof(Data));
    binOut.close();
}

读取二进制数据
Data readData;
std::ifstream binIn("data.bin", std::ios::binary);
if (binIn) {
    binIn.read(reinterpret_cast<char*>(&readData), sizeof(Data));
    binIn.close();
    std::cout << "ID: " << readData.id << ", Value: " << readData.value << "\n";
}


文件状态与模式控制

通过标志位控制文件打开模式:

  • std::ios::app:追加模式
  • std::ios::trunc:覆盖模式(默认)
  • std::ios::ate:打开后定位到文件末尾

检查文件状态:

std::fstream file("test.txt");
if (!file) {
    std::cerr << "Error opening file\n";
}


文件位置操作

使用 seekg()(读位置)和 seekp()(写位置)移动文件指针,配合 tellg()/tellp() 获取当前位置。

std::fstream file("example.txt", std::ios::in | std::ios::out);
file.seekg(0, std::ios::end);  // 移动到文件末尾
size_t size = file.tellg();    // 获取文件大小
file.seekg(0, std::ios::beg);  // 回到文件开头


错误处理

通过检查流状态捕获错误:

  • fail():非致命错误(如类型不匹配)
  • bad():致命错误(如磁盘损坏)
  • eof():到达文件末尾
std::ifstream file("missing.txt");
if (file.fail()) {
    std::cerr << "File operation failed\n";
}

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐