Thread: Whats wrong with my file reading program?

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    57

    Whats wrong with my file reading program?

    It outputs the data correctly into the .txt file. But when reading it. It doesn't come out right.


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    class Data
    {
     public:
     void Output(char*, int);
     void Input(int);
     Data();
     ~Data();
    
     private:
     FILE *out;
     FILE *in;
     int *Age;
     int rand_age;
    
    }dt;
    
    Data:: Data()
    {
     srand((int)time(NULL));
     out= fopen("Stats.txt", "w");
     in= fopen("Stats.txt", "r");
     Age= new int[2];
     rand_age=1 + (rand() % 15) + 10;
    }
    
    void Data::Output(char *Name, int ID)
    {
     Age[ID]= rand_age;
    
     fprintf(out, "Name: %s\n", Name);
     fprintf(out, "Age: %i\n\n", Age[ID]);
    }
    
    void Data::Input(int ID)
    {
     char *Name;
     fscanf(in, "Name: %s\n", Name);
     fscanf(in, "Age: %d\n", Age[ID]);
    
     printf("\nName: %s", Name);
     printf("\nAge: %d\n", Age[ID]);
    }
    
    Data::~Data()
    {
     fclose(out);
     fclose(in);
     delete [] Age;
    }
    
    int main(int argc, char *argv[])
    {
     if(sizeof(Data) > 0)
     {
      dt.Output("Jerome", 0);
      dt.Output("James", 1);
      dt.Input(0);
      dt.Input(1);
     }
    
     printf("\n\n");
     system("pause");
     return EXIT_SUCCESS;
    }
    "A Programmer being told to 'go to' hell sees the 'go to' part of the sentence as the worst part." - Master Foto

  2. #2
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    You're opening the file two times, for reading and writing.

    Do like this:

    1.Open for write
    2.write
    3.Close
    4.Open for read
    5.read
    6.Close
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Something is wrong with my file reverse program
    By abh!shek in forum C Programming
    Replies: 17
    Last Post: 05-21-2008, 11:15 AM
  4. need help reading a file (isbn program)
    By bigmac(rexdale) in forum C Programming
    Replies: 2
    Last Post: 05-16-2008, 10:56 PM
  5. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM