Please help a newby trying to code first program.
I want to be able to write data to a file, then read from the same file.
I can manage this OK, but If I set-up a loop to do the same procedure again I get an error message telling me it cannot open the file for a second time.
Below is a simple form of my problem. I want to write some random numbers to a file, read from it and display the results, then go back and repeat the procedure a user defined number of times. I MUST use the same file though, as I will want to do this loop a great many times.
My code is:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
main ()
{
fstream file1;
fstream file2;
int i, a, b, c, d;
srand(time(NULL));
cout << "how many times ";
cin >> d;
for( c = 1; c <= d;c++ )
{
// *****************************
cout << endl;
cout << " try " << c << " ";
// writing to file
file1.open( "test.dat", ios::out);
if (!file1)
{
cerr << "Unable to open test.dat 1.";
exit(1);
}
for( i = 1; i <= 5;i++ )
{
a = (rand() % 100) + 1; // random nunber from 1 to 100
file1 << a << endl; // write to file
}
file1.close();
// reading from file
file2.open( "test.dat", ios::in);
if (!file2)
{
cerr << "Unable to open test.dat 2.";
exit(1);
}
while( !file2.eof() )
{
file2 >> b;
cout << b << " ";
}
file2.close();
}
}
The output I get (on a PC) is:
How many times 3
try 1 82 62 24 24 40 40
try 2 Unable to open test.dat 2
I have tried everything I know (not much) and really need some help.
John