gpt4 book ai didi

c++ - 简单的 C++ 文件打开问题

转载 作者:行者123 更新时间:2023-11-30 01:31:52 26 4
gpt4 key购买 nike

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
ofstream testfile;
testfile.open ("test.txt");
testfile << "success!\n";
testfile.close();
return 0;
}

1)调用了“g++ testfile.cpp”
2)创建“test.txt”
3) 称为“chmod u+x a.out”
4)???
5)文件保持空白。

我觉得自己像个白痴,因为在这本应该是微不足道的事情上失败了。

最佳答案

执行文件 I/O 时,几乎总是需要测试错误:

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
ofstream testfile;
testfile.open ("test.txt");
if ( ! testfile.is_open() ) {
cerr << "file open failed\n";
return 1;
}

if ( ! testfile << "success!\n" ) {
cerr << "write failed\b";
return 1;
}

testfile.close(); // failure unlikely!
return 0;
}

关于c++ - 简单的 C++ 文件打开问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com