Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

file

file-io

I'm reading source code of the linux tool badblocks. They use the read() function there. Is there a difference to the standard C fread() function? (I'm not counting the arguments as a difference.)

like image 526
Georg Schölly Avatar asked Feb 24 '09 23:02

Georg Schölly


People also ask

What is the use of fread ()?

The fread() function in C++ reads the block of data from the stream. This function first, reads the count number of objects, each one with a size of size bytes from the given input stream.

What does fread () return?

The fread() function returns the number of full items successfully read, which can be less than count if an error occurs, or if the end-of-file is met before reaching count. If size or count is 0, the fread() function returns zero, and the contents of the array and the state of the stream remain unchanged.

What is the difference between fread and fwrite?

The fread( ) function reads a specified number of bytes from a binary file and places them into memory at the specified location. The fwrite( ) function writes a specified number of bytes from the memory address specified and places them into the file.


2 Answers

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.

like image 54
Darron Avatar answered Nov 09 '22 09:11

Darron


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.

like image 41
AIB Avatar answered Nov 09 '22 08:11

AIB