fread records into a struct

This is a discussion on fread records into a struct within the C Programming forums, part of the General Programming Boards category; I can't get this to work.. I have a binary file that I would like to read in to a ...

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    21

    fread records into a struct

    I can't get this to work.. I have a binary file that I would like to read in to a struct. The problem is that I only get the last record and the rest as empty records.. Let me clarify - the last record gets set as the first record and the remaining records are empty. The next record always overwrites the previous record every time through the loop.
    What am I missing here?

    Code:
           fptr = fopen("c:\\test\\runners.bin", "rb");
           while (fread(run, sizeof(struct runners), 1, fptr) == 1)
           {
               run[count];
               count++;
           }
           fclose(fptr);
    If I statically set the amount of records to be read in, it works.
    for example:

    Code:
           fptr = fopen("c:\\test\\runners.bin", "rb");
           fread(run, sizeof(struct runners), 3, fptr);
           fclose(fptr);
           count = 3;
    Please help..

    [Edit]
    Oh, I think I got it!
    Code:
           fptr = fopen("c:\\test\\runners.bin", "rb");
           while (fread(&run[count], sizeof(struct runners), 1, fptr) == 1)
           {
               count++;
           }
           fclose(fptr);
    That seems to work!
    [/Edit]
    Last edited by Machiaveli; 10-14-2006 at 02:37 PM.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Consider also that fread can do the looping internally.
    Code:
       size_t count = fread(run, sizeof *run, array_size, fptr);
       if ( count != array_size )
       {
          /* deal with it */
       }
    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.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. linked list question
    By brb9412 in forum C Programming
    Replies: 16
    Last Post: 01-04-2009, 03:05 PM
  2. Replies: 1
    Last Post: 12-03-2008, 02:10 AM
  3. Replies: 16
    Last Post: 10-29-2006, 04:04 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

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