c++ ifstream open函数出错

来源:百度知道 编辑:UC知道 时间:2024/06/06 23:23:23
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char filename[50],buffer[255];
cout<<"enter file name:";
cin>>filename;

ifstream in(filename);
if(in)
{
cout<<"test:"<<endl;
char ch;
while(in.get(ch))
cout<<ch;
cout<<"the end."<<endl;
}
in.close();

cout<<"opening "<<filename<<" in app..."<<endl;

ofstream out(filename,ios::app);
if(!out)
{
cout<<"error 1..."<<endl;
return 1;
}
cout<<"enter text:";
cin.ignore(1,'\n');
cin.getline(buffer,255);
out<<buffer<<endl;
out.close();

ifstream in(filename);
if(!in)
{
cout<<"error 2..."<<endl; //这

in重复定义不出错?
in.clear(); in.open(.....试试看

改了in.open之后,在我这里运行良好。
sylecn@apu:~/cpp/testing-only$ echo -e "abc\ndef" > tmp
sylecn@apu:~/cpp/testing-only$ ./a.out
enter file name:tmp
test:
abc
def
the end.
opening tmp in app...
enter text:123
new file:
abc
def
123
the end of all
sylecn@apu:~/cpp/testing-only$

这是你想要的结果吗?