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

Recommended Answers

All 2 Replies

why do you close the file? there is a different cursor (wrong technical name I am sure but easier to think about it as a cursor) for inputs and outputs...since u are using fstream instead of ofstream or ifstream, you can read and write with same object. Open the file before the loop, then close it after, move the cursors back to beginning at start of loop with file1.seekp(0L, ios::beg) file1.seekg(0L, ios::beg). This will make teh code neater but I am not sure if that's an actual problem. I can't check it on my own computer since I accidentally delted my C++ software the other day...but only opening it once will make it easier to debug, even if it doesnt solve the problem.

Where do you dig these 2 year old threads from? I am closing this thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.