fread fwrite structure

This is a discussion on fread fwrite structure within the C Programming forums, part of the General Programming Boards category; The regular members to this board, who have been helping me, will kow I am learning to program using arrays ...

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    51

    fread fwrite structure

    The regular members to this board, who have been helping me, will kow I am learning to program using arrays of structures. Well Im still having probs. If someone could please tell me what Im doing wrong I would be so grateful. I have rewritten and recompiled my program so many times I have lost count. I will post just a small sample of the code I am writing.


    Code:
    #include<stdio.h>
    
    struct chris{
           char name[30];
           int age;
           };
           
           FILE *fp;
           int main();
           int i;
          int main() 
    {
           struct chris data[10];
           
           fp = fopen("output.dat", "ab");
           
           for( i = 0; i < 5; i ++ )
           {
                printf("Enter name:");
                scanf("%s", &data[i].name);
                printf("Enter agae:");
                scanf("%d", &data[i].age);
                }
                
                fwrite(data, sizeof(struct chris), 10, fp);
                fclose(fp);
                
                fp = fopen("output.dat", "rb");
                fread(data, sizeof(struct chris), 10, fp);
                for( i = 0; i < 10; i ++){
                printf("%s\n", data[i].name);
                printf("%d", data[i].age);
                getch();
                }
    
    }
    I know that there is lots bad coding here, but this is just an example of what I am doing. Because I know that quzah will probably have lots to say about "this is wrong" and "That is wrong" "You havent fclosed your files" and you dont listen to what I tell you". Well Quzah, I do listen but, the problem is - It will let me input data the first time I execute the code and save it to disk. But the second time round It doesnt seem to register the input to file, but just reads my last input. Somebody please...what am I doing wrong??

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    You write 10 structs, only 5 of which are filled. Then you read them back.
    Then you append 10 structs, only 5 of which are filled. Then you read back the first 10 from the file.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,855
    "ab" is your problem, as you keep running the program you should see your file getting bigger and bigger.

    But your "rb" only ever sees the first 10 records.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    51
    yeah, I noticed the file gets bigger everytime I run the program. So what does "ab" actually do? I thought it would write the data to the next empty structure? Is it wrong that Im using the integer "i" to printf through the array? If so how do I overcome this?

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    You are appending when you write. Do you want to append? Or should you be overwriting the file?

    If you want to append, fine. Write your 5 or 10 structures all at once each time through. When you read, however, you may want to continue reading the 5 or 10 structures until you've gone through all of them. Something like this...
    Code:
       file = fopen(filename, "rb");
       while ( fread(data, sizeof *data, sizeof data / sizeof *data, file)
               == sizeof data / sizeof *data )
       {
          for ( i = 0; i < sizeof data / sizeof *data; ++i )
          {
             printf("%s,%d\n", data[i].name, data[i].age);
          }
       }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,855
    "w" rewrites the file, "a" appends.
    It's all in the manual page.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    Aug 2005
    Posts
    51
    Yeah I do want to append, I will try again using your sample code. Thanks Dave and Salem.

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    This topic has attracted my interest, so here are some ideas from my impression of what you are after.
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    struct record
    {
       char name[30];
       int age;
    };
    
    void record_write(const char *filename)
    {
       FILE *file = fopen(filename, "ab");
       if ( file != NULL )
       {
          struct record data;
          char line [ 20 ];
    
          printf("Enter name: ");
          fflush(stdout);
          if ( fgets(data.name, sizeof data.name, stdin) != NULL )
          {
             char *newline = strchr(data.name, '\n');
             if ( newline != NULL )
             {
                *newline = '\0';
             }
          }
          printf("Enter age: ");
          fflush(stdout);
          fgets(line, sizeof line, stdin);
          sscanf(line, "%d", &data.age);
    
          fwrite(&data, sizeof data, 1, file);
          fclose(file);
       }
    }
    
    void record_readall(const char *filename)
    {
       FILE *file = fopen(filename, "rb");
       if ( file != NULL )
       {
          struct record data;
          while ( fread(&data, sizeof data, 1, file) == 1 )
          {
             printf("%s,%d\n", data.name, data.age);
          }
          fclose(file);
       }
    }
    
    int main()
    {
       static const char filename[] = "output.dat";
       for ( ;; )
       {
          char line[10];
          fputs("Add record (Y/N)? ", stdout);
          fflush(stdout);
          fgets(line, sizeof line, stdin);
          if ( tolower(*line) == 'n' )
          {
             break;
          }
          record_write(filename);
       }
       record_readall(filename);
       return 0;
    
    }
    
    /* my output
    H:\test>Test
    Add record (Y/N)? Y
    Enter name: Dave
    Enter age: 35
    Add record (Y/N)? n
    Dave,35
    
    H:\test>Test
    Add record (Y/N)? Y
    Enter name: Vlad
    Enter age: 39
    Add record (Y/N)? y
    Enter name: Jose
    Enter age: 32
    Add record (Y/N)? n
    Dave,35
    Vlad,39
    Jose,32
    
    H:\test>Test
    Add record (Y/N)? n
    Dave,35
    Vlad,39
    Jose,32
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    Registered User
    Join Date
    Aug 2005
    Posts
    51
    An extended thanks to Dave_Sinkula. This is exactly what I was looking for, I have learnt from this now, and can use it in my program. I think maybe this should go to the FAQ section, as this type of question seems to come about a lot, but the rest of the tutorials dont seem to explain it properly, although Im sure a lot of newbies will learn from this thread.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by voodoo3182
    I know that there is lots bad coding here, but this is just an example of what I am doing. Because I know that quzah will probably have lots to say about "this is wrong" and "That is wrong" "You havent fclosed your files" and you dont listen to what I tell you". Well Quzah, I do listen but, the problem is - It will let me input data the first time I execute the code and save it to disk. But the second time round It doesnt seem to register the input to file, but just reads my last input. Somebody please...what am I doing wrong??
    Quote Originally Posted by Salem
    But your "rb" only ever sees the first 10 records.
    Holy Deja Vu Batman!

    On an aside, why are you asking for help if you don't want to hear what's wrong with it? Rhetorical. Don't bother.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Weird problem with fwrite() and fread()
    By piote in forum C Programming
    Replies: 2
    Last Post: 11-13-2004, 03:07 PM
  2. buffer type for fread & fwrite
    By daluu in forum C Programming
    Replies: 5
    Last Post: 05-08-2003, 07:57 PM
  3. saving structure with fwrite
    By GaPe in forum C Programming
    Replies: 3
    Last Post: 02-26-2003, 11:20 AM
  4. Serial Communications in C
    By ExDigit in forum Windows Programming
    Replies: 7
    Last Post: 01-09-2002, 10:52 AM
  5. fread() and fwrite() ?
    By Limblet in forum C Programming
    Replies: 4
    Last Post: 09-25-2001, 08:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21