C++在Linux中的文件操作方法
作者:SunnyJourney
时间:2026-07-12
浏览:0
在Linux环境下,C++通过std::ifstream、std::ofstream和std::fstream实现文件读写。打开文件后可用运算符>>按格式读取,或使用std::getline()逐行处理文本数据,支持文本与二进制模式,需注意关闭文件。
本文目录
在 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++ 文件操作的核心套路。实际项目中根据需求组合这些方法,绝大多数场景都能轻松拿下。
作者最新文章
漫蛙下载最新版本
2026-10-13 13:42
漫蛙app下载安装最新版
2026-10-13 13:42
漫蛙2漫画APP免费下载安装最新版本
2026-10-13 13:20
漫蛙漫画网页下载安装最新版本
2026-10-13 13:17
keyshot快捷键命令大全表格整理与使用教程
2026-10-12 14:13
上一篇:
Golang在Debian打包的性能如何
下一篇:
C++在Linux下的异常处理机制
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































