#include <iostream>
#include <fstream>
int main() {
// 创建文件
std::ofstream outfile("example.txt");
if (outfile.is_open()) {
std::cout << "文件创建成功" << std::endl;
// 写入数据
outfile << "Hello, world!" << std::endl;
// 关闭文件
outfile.close();
std::cout << "文件已关闭" << std::endl;
} else {
std::cerr << "文件创建失败" << std::endl;
}
// 打开文件
std::ifstream infile("example.txt");
if (infile.is_open()) {
std::cout << "文件打开成功" << std::endl;
// 读取数据
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
// 关闭文件
infile.close();
std::cout << "文件已关闭" << std::endl;
} else {
std::cerr << "文件打开失败" << std::endl;
}
return 0;
}
在上面的示例中,我们使用std::ofstream
创建一个文件并写入数据,然后使用std::ifstream
打开该文件并读取数据。最后,关闭文件流以释放资源。