john smith john smith - 22 days ago 11
C++ Question

C++ reading an output file which should already exist

How do prompt the user to enter the name of the output file and IF not found retry?

Every time this happens it just creates the output file; which i dont want i only want it to read the output file.

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());


This is what the output should be

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

Answer

Looks like you are using ofstream fileout; which overwrites existing file by default. To achieve desired behavior you could use fstream and specify both in | out flags:

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

This is the default flags used by fstream.open, so you can just write:

fileout.open(nameoutputfile);