What is the difference between read() and fread()?

read is a syscall, whereas fread is a function in the C standard library.


read() is a low level, unbuffered read. It makes a direct system call on UNIX.

fread() is part of the C library, and provides buffered reads. It is usually implemented by calling read() in order to fill its buffer.


As I remember it the read() level APIs do not do buffering - so if you read() 1 byte at a time you will have a huge perf penalty compared to doing the same thing with fread(). fread() will pull a block and dole it out as you ask for it. read() will drop to the kernel for each call.


Family read() -> open, close, read, write
Family fread() -> fopen, fclose, fread, fwrite

Family read:

  • are system calls
  • are not formatted IO: we have a non formatted byte stream

Family fread

  • are functions of the standard C library (libc)
  • use an internal buffer
  • are formatted IO (with the "%.." parameter) for some of them
  • use always the Linux buffer cache

More details here, although note that this post contains some incorrect information.

Tags:

C

File

File Io