Understanding fread() C Function for Binary File Reading

  • Thread starter Thread starter Adyssa
  • Start date Start date
  • Tags Tags
    Function
Click For Summary
SUMMARY

The forum discussion centers on the proper usage of the C function fread() for reading binary files. The correct function signature is size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream), where size represents the size of each element and nmemb represents the number of elements to read. A common mistake identified is reversing the parameters, which leads to incorrect byte reading. The correct call should be fread(record_array, sizeof(record), num_records, myfile) to read the expected number of bytes.

PREREQUISITES
  • Understanding of C programming language
  • Familiarity with file I/O operations in C
  • Knowledge of binary file formats
  • Experience with data structures in C
NEXT STEPS
  • Review the C standard library documentation for fread()
  • Learn about error handling in file I/O operations in C
  • Explore the differences between reading binary and text files in C
  • Investigate the use of fwrite() for writing binary data
USEFUL FOR

C programmers, software developers working with binary data, and anyone involved in file I/O operations in C will benefit from this discussion.

Adyssa
Messages
202
Reaction score
3
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?
 
Technology news on Phys.org
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.
 
Oooh I missed that, thanks. Also, they were reversed /facepalm. =S

It's been a long day! :)
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
6K
  • · Replies 31 ·
2
Replies
31
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
Replies
10
Views
2K
Replies
20
Views
2K
  • · Replies 5 ·
Replies
5
Views
8K
  • · Replies 57 ·
2
Replies
57
Views
6K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 19 ·
Replies
19
Views
4K