Gau*_*rav 2 c++ file-io fstream
但他们的回答都没有帮助我。在调试了这么多小时后,我无法检测到错误。所以,我再次在这里问它。
我的程序的代码是:
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main(){
ofstream file;
file.open("data.dat",fstream::out);
file<<fflush;
if(!file)
cout<<"error"<<strerror(errorno);
file.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是处理文件处理的程序的主要部分。程序的其余部分处理一些数据并将其写入文件,我认为这既不相关也不影响文件处理。
有趣的是程序没有闪烁任何错误。
您的代码通常只需要少量更改,文件只是在运行程序的当前工作目录中创建,而不是在可执行文件所在的目录中创建。不过,您可能还需要解决很多其他问题:
#include <iostream>
#include <fstream>
// if including things from the C standard library in a C++ program,
// use c[header] instead of [header].h; you don't need any here though.
using namespace std;
int main()
{
// no need to call open(), the constructor is overloaded
// to directly open a file so this does the same thing
ofstream file("data.dat");
if(!file)
{
cout << "Couldn't open file" << endl;
return 1;
}
file.close();
// return 0; is not needed, your program will automatically
// do this when there is no return statement
}
Run Code Online (Sandbox Code Playgroud)
有关打开文件不起作用的原因的详细信息,您可以查看std::basic_ios::bad()和std::basic_ios::fail()。errno使用 C++ 流进行文件处理时,您不需要进行检查。