c++ fopen出错

来源:百度知道 编辑:UC知道 时间:2024/06/17 17:26:12
void main()
{
FILE * fp;
char ch;
if((fp=fopen("a.txt","r"))==NULL)
{
printf("error\n");
}
else
{
ch=fgetc(fp);
fclose(fp);
}

}
总显示error

把路径设置对就OK了
fp=fopen("a.txt","r"))时跟debug放在同一目录

a.txt在程序运行目录下吗?

c++一般不用fopen,倒是c里面常用。
c++一般喜欢用ofstream类。
源代码更改如下:

#include <fstream>
#include <iostream>
#Include <string>

using namespace std;

int main ()
{
string x;
ofstream fout ("a.txt",ios::nocreate);
if (!fout)
{
cout<<"error\n";
}
else
{
cin>>x;
fout<<x;
fout.close();
}
system ("pause");
return 0;
}

// (我这个是绝对的c++用法)