C++文件操作全解析:读写模式与实战技巧

在 C++ 中,文件操作主要通过 <fstream> 头文件提供的流类实现。以下是主要类和打开方式:

一、核心流类

  1. ifstream
    用于读取文件(输入流),继承自 istream
    $$ \text{ifstream} \subset \text{istream} $$

  2. ofstream
    用于写入文件(输出流),继承自 ostream
    $$ \text{ofstream} \subset \text{ostream} $$

  3. fstream
    支持读写操作(双向流),继承自 iostream
    $$ \text{fstream} \subset \text{iostream} $$


二、文件打开模式

通过位或运算符 | 组合模式标志:

std::ios::in      // 读模式(默认 ifstream)
std::ios::out     // 写模式(默认 ofstream)
std::ios::app     // 追加写入(尾部插入)
std::ios::ate     // 打开后定位到文件尾
std::ios::trunc   // 清空文件(默认 ofstream)
std::ios::binary  // 二进制模式

三、打开方式示例

1. 写入文件(覆盖模式)
#include <fstream>
int main() {
    std::ofstream file("data.txt", std::ios::out | std::ios::trunc);
    if (file.is_open()) {
        file << "Hello, C++!" << std::endl;
        file.close();
    }
    return 0;
}
2. 追加写入
std::ofstream file("log.txt", std::ios::app);
file << "New log entry" << std::endl;
3. 读取文件
std::ifstream file("config.ini");
std::string line;
while (std::getline(file, line)) {
    std::cout << line << std::endl;
}
4. 读写混合操作
std::fstream file("data.db", 
                  std::ios::in | std::ios::out | 
                  std::ios::binary);

四、错误检测

if (!file) {
    std::cerr << "文件打开失败" << std::endl;
}
// 检查流状态
if (file.fail()) { /* 操作失败处理 */ }
if (file.eof())  { /* 到达文件尾 */ }

五、二进制文件操作

struct Record { int id; char name[32]; };
// 写入二进制数据
Record r = {1, "Alice"};
file.write(reinterpret_cast<char*>(&r), sizeof(Record));
// 读取二进制数据
Record data;
file.read(reinterpret_cast<char*>(&data), sizeof(Record));

注意:二进制操作需确保数据内存布局对齐,跨平台时需谨慎处理字节序。

© 版权声明

相关文章