#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)文件保持空白。
我觉得自己像是一个傻瓜,因为这应该是一件微不足道的事情。
答案 0 :(得分: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;
}
答案 1 :(得分:0)
理论上它们是等价的,但只是为了确保,请尝试<< endl
而不是"\n"
来刷新流。
ofstream testfile;
testfile.open ("test.txt");
testfile << "success!" << endl;
testfile.close();