fread() C function


by Adyssa
Tags: fread, function
Adyssa
Adyssa is offline
#1
Mar16-12, 06:18 AM
P: 186
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?
Phys.Org News Partner Science news on Phys.org
Going nuts? Turkey looks to pistachios to heat new eco-city
Space-tested fluid flow concept advances infectious disease diagnoses
SpaceX launches supplies to space station (Update)
D H
D H is online now
#2
Mar16-12, 06:54 AM
Mentor
P: 14,440
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.
Adyssa
Adyssa is offline
#3
Mar16-12, 08:03 AM
P: 186
Oooh I missed that, thanks. Also, they were reversed /facepalm. =S

It's been a long day! :)


Register to reply

Related Discussions
prove that derivative of the theta function is the dirac delta function Advanced Physics Homework 3
Approximating the probability density function from the moment generating function Set Theory, Logic, Probability, Statistics 6
Square of the Riemann zeta-function in terms of the divisor summatory function. Linear & Abstract Algebra 6
[matlab] I just want to plot a function that describes position as a function of time Math & Science Software 2
Determine a function that calculates the nth weight factor of a wave function Advanced Physics Homework 0