Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Fread() C function

  1. Mar 16, 2012 #1
    I'm reading a binary file with fread, and I'm getting some strange results. This is from the man page:

    size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

    The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.


    I understand it to read (nmemb * size) bytes from the file and I'm trying to use it like this:

    fread(record_array, num_records, sizeof(record), myfile)

    and I'm expecting to read (num_records * sizeof(record)) bytes, call it 10 * 50 = 500.

    However, when I do this, it only reads sizeof(record) (50) bytes. If I call it like this it works fine (many elements of size 1 byte each):

    fread(record_array, 1, (num_records * sizeof(record)), myfile)

    so it seems to ignore the 2nd function parameter. Weird? It's not killing me, but I'm not sure why the size_t size variable is redundant?
     
  2. jcsd
  3. Mar 16, 2012 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    You are calling fread with the size and nmemb arguments reversed. Your call should be fread (record_array, sizeof(record), num_records, myfile).

    The return value from fread is the number of records that were read, not the number of bytes.
     
  4. Mar 16, 2012 #3
    Oooh I missed that, thanks. Also, they were reversed /facepalm. =S

    It's been a long day! :)
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Fread() C function
  1. C++ function (Replies: 3)

  2. Functions in c (Replies: 1)

  3. C# with C++ functions (Replies: 2)

  4. Random function in C (Replies: 31)

Loading...