C ++读取应该已经存在的输出文件

时间:2016-11-16 04:58:15

标签: c++ visual-studio c++11

如何提示用户输入输出文件的名称并且IF未找到重试?

每次发生这种情况时,它只会创建输出文件;我不想要我只想要它读取输出文件。

do{
cout <<"Type the name of the output file which will hold the simulation             results:\n";
cin >> nameoutputfile;
fileout.open(nameoutputfile);

if (fileout.fail())
{
cout << "ERROR: File "<< nameoutputfile <<" could not be opened\n";
tries[1]++;
}
if (tries[1] == trylimit)
{
cout << "ERROR: You exceeded maximum number of tries allowed\n";
cout << "while entering the input file name";
return 2;
}
}while(fileout.fail());

这就是输出

outputReadOnly.txt   
ERROR: File outputReadOnly.txt could not be opened    
Type the name of the output file which will hold the simulation results:  
outputReadOnly.txt  
ERROR: File outputReadOnly.txt could not be opened  
Type the name of the output file which will hold the simulation results:  
outputReadOnlyt.txt  
ERROR: You exceeded maximum number of tries allowed  
while entering the output file name 

1 个答案:

答案 0 :(得分:0)

您似乎正在使用ofstream fileout;默认覆盖现有文件。要实现所需的行为,您可以使用fstream并指定两个in | out标志:

fstream fileout;
do{
  // Other code skipped for simplicity
  fileout.open(nameoutputfile, ios_base::in|ios_base::out);
  // ...
}while(fileout.fail());

这是fstream.open使用的默认标志,因此您只需编写:

fileout.open(nameoutputfile);