Thread: Reading a binary file

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    20

    Question Reading a binary file

    This is probably very simple, but I need to know where I'm going wrong.

    I have a structure and a binary file containing lots of records. I want to read one record from the file into the structure, use the information in the structure, and then read another record (the next one) from the file into the structure.

    This is my code:

    #define REC_SIZE(sizeof(a_rec))

    typedef struct{
    char...;
    char...;
    float...;
    int...;
    }a_rec;

    FILE *fp;


    void main()
    {

    a_rec cust_rec;
    a_rec *a_rec_ptr = &cust_rec;

    /*open file*/

    fread(a_rec_ptr, REC_SIZE, 1, fp);

    /*then use data in structure, then read next record for use*/

    fread(a_rec_ptr, REC_SIZE, 1, fp);

    fclose(fp);
    }

    Why won't it read the next record in the binary file? The file pointer continues to point at the beginning of the same record.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    fread returns a success/fail status - check it.

    If it returns fail, use feof() and ferror() to work out why.

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    32

    ?Reading a binary file

    The way to increment the pointer is to place fread in a while loop that will stop looping when you are at the end of the file and have read in the last record. FREAD returns the number of items read in, in your case 1. When the end of the file is reached FREAD can no longer return 1. So the loop stops.

    while( fread( a_rec_ptr, REC_SIZE, 1, fp) == 1 )
    {

    /*then use data in structure, then read next record for use*/
    }

    In your coding you have declared a structure of type a_rec and then declared an identifier called cust_rec. With this in mind you might want to fread directly into the identifier cust-rec

    If so ?while( fread( a_rec_ptr, REC_SIZE, 1, fp) == 1 )? would be replaced with
    while( fread(&cust_rec, REC_SIZE, 1, fp) == 1 )
    {
    }

    Good luck

    Stephanos

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary Tree - Reading From and Writing to a File
    By Ctank02 in forum C++ Programming
    Replies: 2
    Last Post: 03-15-2008, 09:22 PM
  2. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  3. Problem reading a delimited file into a binary tree
    By neolyn in forum C++ Programming
    Replies: 10
    Last Post: 12-09-2004, 07:51 PM
  4. Reading data from a binary file
    By John22 in forum C Programming
    Replies: 7
    Last Post: 12-06-2002, 02:00 PM
  5. reading from structs in a binary file
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 12-21-2001, 10:52 AM