引言
文件系统操作是任何应用程序编程中的关键任务之一。在 C++ 中,有两种主要方法:经典方法(使用 <fstream> 库)和现代方法(使用 <filesystem> 库,从 C++17 标准开始可用)。在本文中,我们将通过实际示例来讲解如何读写文件、创建和删除目录,以及检查文件是否存在。
本材料既适合刚学习 C++ 的初学者,也适合希望重温该语言现代功能的有经验的开发者。
1. 使用 fstream 读写文本文件
<fstream> 库提供了用于文件操作的类:ifstream(读取)、ofstream(写入)和 fstream(读写)。
1.1. 将数据写入文件
要写入文件,我们使用 ofstream 对象。如果文件不存在,它将被创建。如果存在,内容将被覆盖(默认情况下)。
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream outFile("example.txt");
if (!outFile.is_open()) {
std::cerr << "打开文件错误!" << std::endl;
return 1;
}
outFile << "你好,世界!" << std::endl;
outFile << "这是第二行。" << std::endl;
outFile.close();
std::cout << "数据已写入。" << std::endl;
return 0;
}
请注意:我们始终检查文件是否成功打开,并在使用后将其关闭。
1.2. 从文件读取数据
要读取数据,我们使用 ifstream。最简单的方法是使用 std::getline 逐行读取。
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("example.txt");
if (!inFile.is_open()) {
std::cerr << "打开文件错误!" << std::endl;
return 1;
}
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
return 0;
}
这种方法很方便,因为它会自动处理文件结尾,无需额外检查。
1.3. 文件打开模式
您可以组合标志来控制打开模式。例如,要将数据追加到文件末尾(追加模式),请使用 std::ios::app 标志:
std::ofstream outFile("example.txt", std::ios::app);
outFile << "附加行。" << std::endl;
outFile.close();
其他有用的标志:std::ios::binary(二进制模式)、std::ios::trunc(打开时清空文件)。
2. 现代文件系统操作(C++17 和 filesystem)
<filesystem> 库大大简化了文件和文件夹的操作。所有函数都位于 std::filesystem 命名空间中。
2.1. 检查文件或目录是否存在
exists() 函数在对象存在时返回 true:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
std::string path = "example.txt";
if (fs::exists(path)) {
std::cout << "文件存在。" << std::endl;
} else {
std::cout << "未找到文件。" << std::endl;
}
return 0;
}
2.2. 创建和删除目录
要创建文件夹,请使用 create_directory()。要删除,请使用 remove() 或 remove_all()(递归删除)。