发布于2026-07-12 阅读(0)
扫一扫,手机访问
在Linux环境下用C++做文件操作,其实是很多开发者日常绕不开的基础活。但别看它基础,真要写得稳、不出bug,还是有不少细节值得留意的。下面就把这些常见操作梳理一遍,算是给刚入门的朋友一份实用参考。

先说说最核心的头文件——。它几乎包办了所有文件读写相关的功能,配合使用,基本就够用了。
#include
#include
接下来是创建文件流对象。根据不同用途,有三个选择:
std::ofstream outFile; // 写文件
std::ifstream inFile; // 读文件
std::fstream file; // 读写皆可
打开文件时,记得指定模式——是只写、只读,还是读写兼可:
outFile.open("example.txt", std::ios::out);
inFile.open("example.txt", std::ios::in);
file.open("example.txt", std::ios::in | std::ios::out);
打开之后别急着操作,先确认文件是否真的打开了。经验表明,很多诡异问题都出在打开失败却没检查:
if (!outFile.is_open()) {
std::cerr << "Error opening file for writing!" << std::endl;
}
if (!inFile.is_open()) {
std::cerr << "Error opening file for reading!" << std::endl;
}
写入文件很简单,和向控制台输出差不多:
outFile << "Hello, World!" << std::endl;
读取时,最常用的方式是按行读取:
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
操作完毕,记得关闭文件——这不是形式,而是释放系统资源的必要步骤:
outFile.close();
inFile.close();
file.close();
如果涉及二进制文件,比如读写图像或序列化数据,打开时加上std::ios::binary模式:
std::ofstream binaryOut("example.bin", std::ios::binary);
std::ifstream binaryIn("example.bin", std::ios::binary);
获取文件大小也是常见需求。可以用seekg和tellg组合实现,注意事后把读取位置重置回开头:
std::ifstream::pos_type fileSize = inFile.seekg(0, std::ios::end).tellg();
inFile.seekg(0, std::ios::beg);
如果想在文件内部随机跳转、读取特定位置的数据,可以用seekg配合read:
file.seekg(10, std::ios::beg);
int value;
file.read(reinterpret_cast(&value), sizeof(value));
判断是否读到文件末尾,可以用eof():
if (inFile.eof()) {
std::cout << "Reached end of file." << std::endl;
}
当然,文件操作难免遇到异常情况。用fail()可以检查是否发生了读取错误:
if (inFile.fail()) {
std::cerr << "An error occurred while reading the file." << std::endl;
}
以上这些就是C++文件操作最常用的基础技巧。在实际项目中,你可能还会遇到大文件处理、多线程并发访问等更复杂的场景。但无论如何,时刻检查文件流的状态、确保资源正确释放,都是贯穿始终的原则。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8