在 Linux 环境下用 C++ 做文件操作, 这个头文件是绕不开的。它提供了文件输入输出所需的核心类与函数,说白了,几乎所有读写文件的需求都要靠它实现。下面把最常用的几个操作拆开来讲,每一步都配有代码,方便直接上手。

-
打开文件:根据用途选择对应的类——只读用
std::ifstream,只写用std::ofstream,读写兼用则用std::fstream。打开后记得检查是否成功,否则后续操作可能踩坑。#include#include int main() { std::ifstream inputFile("example.txt"); // 打开一个用于读取的文件 if (!inputFile.is_open()) { std::cerr << "Unable to open file for reading!" << std::endl; return 1; } std::ofstream outputFile("output.txt"); // 打开一个用于写入的文件 if (!outputFile.is_open()) { std::cerr << "Unable to open file for writing!" << std::endl; return 1; } std::fstream file("example.txt", std::ios::in | std::ios::out); // 打开一个用于读写的文件 if (!file.is_open()) { std::cerr << "Unable to open file for reading and writing!" << std::endl; return 1; } return 0; } -
读取文件:最简单的方式是用
>>操作符逐词读取,但更常见的是按行读取——std::getline()函数会帮你搞定。一行一行处理,清晰又可控。std::string line; while (std::getline(inputFile, line)) { std::cout << line << std::endl; } -
写入文件:和向控制台输出一样简单,直接用
<<操作符往文件流里塞数据就行。注意别忘了加std::endl换行,或者自己控制格式。outputFile << "Hello, World!" << std::endl; -
关闭文件:文件操作完成后,释放资源是必须的。好消息是,当
std::ifstream、std::ofstream或std::fstream对象离开作用域时,析构函数会自动关闭文件。不过,如果代码逻辑复杂,显式调用close()更稳妥,能避免资源被意外占用。inputFile.close(); outputFile.close(); file.close(); -
检查文件状态:读写过程中间出错了怎么办?
eof()判断是否读到文件末尾,fail()检测逻辑错误(比如格式不匹配),bad()则反映更严重的底层问题。养成习惯,操作后顺手检查一下,能省去不少调试时间。if (inputFile.eof()) { std::cout << "Reached end of file." << std::endl; } if (inputFile.fail()) { std::cout << "An error occurred while reading the file." << std::endl; } -
随机访问文件:如果你需要跳着读写,
std::fstream的seekg和seekp就是你的翅膀。前者移动读取位置,后者移动写入位置,配合std::ios::beg(开头)、std::ios::cur(当前位置)、std::ios::end(末尾)使用。比如直接定位到第10个字节读数据,或者在第20个字节处写入一个整数。file.seekg(10, std::ios::beg); // 将读取位置移动到文件的第10个字节 file.seekp(20, std::ios::beg); // 将写入位置移动到文件的第20个字节 int value = 42; file.write(reinterpret_cast(&value), sizeof(value)); // 写入一个整数
以上是 C++ 文件操作中最基础也最常用的几个套路。实际项目中,你可能还需要处理二进制文件、追加模式、缓冲区刷新等细节,但万变不离其宗——记住打开文件要检查、操作完要关闭,这两条做好了,基本就不会出大问题。