C++ 文件操作:写入、读取和文件是否存在判断
C++ 文件操作:写入、读取和文件是否存在判断
本教程将演示如何使用 C++ 的 ofstream 和 ifstream 类来进行文件操作。
1) 使用 ofstream 的构造函数打开 D:\out.txt 文件进行写入
#include <fstream>
int main() {
std::ofstream outfile("D:\out.txt");
// 写入内容
outfile << "Hello, world!" << std::endl;
// 关闭文件
outfile.close();
return 0;
}
2) 使用 ifstream 的 open() 函数打开 x.json 文件进行读取
#include <fstream>
int main() {
std::ifstream infile;
infile.open("x.json");
// 读取内容
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
// 关闭文件
infile.close();
return 0;
}
3) 判断 x.json 文件是否存在,如果不存在输出 'x.json does not exist' 并退出程序
#include <fstream>
#include <iostream>
int main() {
std::ifstream infile("x.json");
if (!infile.good()) {
std::cout << "x.json does not exist" << std::endl;
return 1;
}
// 读取内容
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
// 关闭文件
infile.close();
return 0;
}
总结:
本教程展示了如何使用 C++ 的 ofstream 和 ifstream 类来进行文件操作,包括写入、读取和判断文件是否存在。你可以根据自己的需求修改代码。
原文地址: http://www.cveoy.top/t/topic/nuV2 著作权归作者所有。请勿转载和采集!