发布于2026-07-12 阅读(0)
扫一扫,手机访问
在 Linux 环境下用 C++ 搞文件操作,标准库里的 就是最趁手的工具。下面把这几个基础操作捋一遍,代码直接贴,拿过去就能用。

打开文件
用 std::ifstream(读取)、std::ofstream(写入)或者 std::fstream(读写兼顾)来打开文件。比如说,想读取 example.txt,代码长这样:
#include
#include
int main() {
std::ifstream inputFile("example.txt");
if (!inputFile.is_open()) {
std::cerr << "Error opening file!" << std::endl;
return 1;
}
// ... 进行文件操作 ...
inputFile.close();
return 0;
} 关闭文件
操作完后记得调用 close(),养成好习惯:
inputFile.close();读取文件
两种常用方式:用 >> 运算符按格式读,或者用 std::getline() 按行读。下面示范逐行读取:
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}写入文件
用 << 运算符直接往文件里灌内容:
std::ofstream outputFile("output.txt");
outputFile << "Hello, World!" << std::endl;
outputFile.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;
}
if (inputFile.bad()) {
std::cout << "A serious error occurred with the file." << std::endl;
}定位文件指针
想跳着读或写?用 seekg() 和 seekp() 指定偏移位置,例如:
// 把输入文件指针移到第10个字节
inputFile.seekg(10, std::ios::beg);
// 把输出文件指针移到第20个字节
outputFile.seekp(20, std::ios::beg);以上就是 Linux 下 C++ 文件操作的核心套路。实际项目中根据需求组合这些方法,绝大多数场景都能轻松拿下。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8