在C++中处理文件系统:从基础到高级技术
文件系统操作是任何严肃C++应用程序中的关键任务之一。无论是读取配置文件、写入日志、处理大量数据还是管理项目,正确与文件和目录交互的能力是每个C++开发人员必备的技能。在本文中,我们将探讨C++中处理文件系统的主要方法,从经典的C函数开始,一直到C++17中引入的现代std::filesystem。
我们将研究实际示例,这些示例不仅帮助您理解理论,还能立即将所学知识应用到实际项目中。所有代码示例都经过测试并可供使用。
1. 文件操作基础:输入/输出流
C++中最常见的文件操作方式是使用<fstream>库。它提供了三个主要类:
std::ifstream— 用于从文件读取(输入文件流);std::ofstream— 用于写入文件(输出文件流);std::fstream— 用于读取和写入(文件流)。
从文件读取
要从文件读取数据,创建一个std::ifstream对象并打开文件。逐行读取文件的最简单方法是使用std::getline函数:
#include <iostream>#include <fstream>#include <string>
int main() { std::ifstream inputFile("example.txt"); if (!inputFile.is_open()) { std::cerr << "Ошибка открытия файла!" << std::endl; return 1; }
std::string line; while (std::getline(inputFile, line)) { std::cout << line << std::endl; }
inputFile.close(); return 0;}请注意is_open()检查——这是一种重要的实践,可以防止文件不存在时程序崩溃。
写入文件
要写入数据,使用std::ofstream。默认情况下,文件会被重新创建(trunc模式)。如果需要在文件末尾追加数据,请使用std::ios::app标志:
#include <iostream>#include <fstream>
int main() { std::ofstream outputFile("output.txt", std::ios::app); if (!outputFile.is_open()) { std::cerr << "Ошибка создания файла!" << std::endl; return 1; }
outputFile << "Строка 1" << std::endl; outputFile << "Строка 2" << std::endl; outputFile << "Число: " << 42 << std::endl;
outputFile.close(); return 0;}处理二进制文件
对于二进制数据,使用read()和write()方法并指定块大小:
#include <iostream>#include <fstream>#include <cstring>
struct Record { int id; char name[50]; double value;};
int main() { // 写入 Record r = {1, "Тестовая запись", 3.14}; std::ofstream binOut("data.bin", std::ios::binary); binOut.write(reinterpret_cast<const char*>(&r), sizeof(r)); binOut.close();
// 读取 Record r2; std::ifstream binIn("data.bin", std::ios::binary); binIn.read(reinterpret_cast<char*>(&r2), sizeof(r2)); binIn.close();
std::cout << "ID: " << r2.id << ", Name: " << r2.name << ", Value: " << r2.value << std::endl; return 0;}2. 现代方法:std::filesystem库 (C++17)
从C++17开始,标准库中加入了<filesystem>,它大大简化了文件系统操作。O