悠悠楠杉
网站页面
在C++标准库中,<fstream>
头文件提供了文件流操作类。其中ifstream
专用于文件读取(input file stream),而ofstream
则负责文件写入(output file stream)。这两种类型都继承自iostream
基类,因此可以使用类似的流操作符。
实际开发中,文件操作通常遵循"打开-处理-关闭"的标准流程。这个模式看似简单,但涉及资源管理、异常处理等关键细节,值得我们深入探讨。
cpp
void writeToFile() {
// 创建输出文件流对象
std::ofstream outFile;
// 打开文件(若不存在则创建)
outFile.open("example.txt");
// 检查文件是否成功打开
if (!outFile.is_open()) {
std::cerr << "文件打开失败" << std::endl;
return;
}
// 写入数据
outFile << "第一行文本\n";
outFile << "第二行内容 " << 42 << "\n";
// 显式关闭文件(析构时也会自动关闭)
outFile.close();
}
ios::out | ios::trunc
):ios::app
:追加模式ios::binary
:二进制模式cpp
void readFromFile() {
std::ifstream inFile;
inFile.open("example.txt");
if (!inFile) { // 更简洁的检查方式
std::cerr << "文件读取失败" << std::endl;
return;
}
std::string line;
while (getline(inFile, line)) {
std::cout << "读取到: " << line << '\n';
}
inFile.close(); // 良好的编程习惯
}
inFile >> word
read()
eof()
, fail()
, bad()
seekg()
, tellg()
文件操作可能遇到各种意外情况,推荐使用RAII(资源获取即初始化)模式:
cpp
void safeFileOperation() {
try {
std::ofstream outFile("data.log");
if (!outFile) throw std::runtime_error("文件创建失败");
// 文件操作...
} catch (const std::exception& e) {
std::cerr << "错误: " << e.what() << std::endl;
}
// 无需显式close,RAII自动处理
}
<filesystem>
(C++17)进行跨平台路径操作通过掌握这些基础但关键的文件操作技术,开发者可以构建更健壮的I/O处理模块。记住,良好的资源管理习惯(如及时关闭文件)能有效避免许多潜在问题。