文件操作

内容简介

文件操作用于把数据保存到磁盘,或从磁盘读取数据。学习 C++ 时先掌握文件流 std::ifstreamstd::ofstream,再了解 C 风格的 FILE*fopen/fclose

用法

C++ 写文件

#include <fstream>
 
int main()
{
    std::ofstream out("test.txt");
    out << "hello" << std::endl;
    return 0;
}

C++ 读文件

#include <fstream>
#include <iostream>
#include <string>
 
int main()
{
    std::ifstream in("test.txt");
    if (!in.is_open()) {
        return 1;
    }
 
    std::string line;
    while (std::getline(in, line)) {
        std::cout << line << std::endl;
    }
 
    return 0;
}

C 风格写文本文件

#include <stdio.h>
 
int main(void)
{
    FILE *fp = fopen("test.txt", "w");
    if (fp == NULL) {
        return 1;
    }
 
    fprintf(fp, "hello\n");
    fclose(fp);
    return 0;
}

C 风格读文本文件

#include <stdio.h>
 
int main(void)
{
    FILE *fp = fopen("test.txt", "r");
    if (fp == NULL) {
        return 1;
    }
 
    char line[256];
    while (fgets(line, sizeof(line), fp) != NULL) {
        printf("%s", line);
    }
 
    fclose(fp);
    return 0;
}

最佳代码实践

  • C++ 优先使用文件流对象,让析构函数自动关闭文件。
  • 打开文件后立刻检查是否成功。
  • C 代码中每个成功打开的 FILE* 都要 fclose
  • 读文本文件优先按行读取,避免固定缓冲区不够。
  • 二进制文件读写要使用 std::ios::binary
std::ofstream out("data.bin", std::ios::binary);

错误用法

FILE *fp = fopen("test.txt", "r");
fprintf(fp, "hello");  // 错误:没有检查 fp 是否为 NULL,而且 r 模式不能写
std::ifstream in("test.txt");
std::string text;
in >> text;  // 不一定错误,但只能读到空白字符前,不能读取整行

注意事项

  • C++ 文件打开模式常用:std::ios::instd::ios::outstd::ios::appstd::ios::binarystd::ios::trunc
  • 不要用二进制方式直接保存包含指针、虚函数或复杂对象的内存布局;跨平台和跨版本都不稳定。
  • 文件路径相对当前工作目录,不一定是源文件所在目录。

学习路径