1、当文件名称已经存在,且磁盘已满,is_open返回true
2、当文件名不存在,磁盘已满,is_open返回false
为了避免这种现象发生,注意先判断磁盘空间
#include <fstream>
#include <filesystem>
int main() {
std::string filename = "myfile.txt";
// 检查磁盘空间是否足够
std::filesystem::space_info space_info = std::filesystem::space(".");
if (space_info.available < 1024) {
std::cout << "磁盘空间不足,无法写入文件。" << std::endl;
return 1;
}
// 打开文件
std::ofstream file(filename);
if (!file.is_open()) {
std::cout << "无法打开文件。" << std::endl;
return 1;
}
// 写入文件
file << "Hello world!";
// 关闭文件
file.close();
return 0;
}