freopen()能读取文件中的内容
当使用freopen()读取多个文件时,每读取完一个文件后,要使用cin.clear()清空流,否则即使应用了if,也不会显示文件打开失败;或是即使运用了fclose(),也不会读取下一个文件。
当使用freopen()读取完文件后还需要读取控制台输入的指令时,就要使用freopen("CON","r",stdin);来返回控制台,否则,其不会读取控制台命令。
if(freopen("input.txt","r",stdin)==NULL)
{
cout<<"文件打开失败"<<endl;
}
fclose(stdin);
cin.clear();
freopen("CON","r",stdin);
写文件同理:
//freopen("out.txt","W",stdout);//写文件
if(freopen("out.txt","W",stdout))==NULL)
{
cout<<"文件打开失败"<<endl;
}
fclose(stdin);
cin.clear();
freopen("CON","r",stdin);