tags:

views:

2106

answers:

4

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.)

+1  A: 

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

phihag
+12  A: 

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.

Darron
So there are 3 buffers? The harddrive has one, /dev/hda is buffered too and fread. Is this correct?
Georg
yes. you can flush the third one using "fflush", the second one using fsync. i don't know of a way to flush the harddrive buffer.
Johannes Schaub - litb
fflush() only really applies to fwrite(), which has the same relation to write() that fread() has to read().
Darron
+3  A: 

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.

Joe
+3  A: 

Default read API vs fread APIs

  1. Family read and Co: open, close, read, write, ioctl...
  2. Family fread and Co: fopen, fclose, fread, swrite, fcntl...

Family read and Co: - are syscalls. - are not formatted IO : we have a non formatted byte stream. - don't use the Linux buffer cache. - generally used for accessing character devices.

Family fread and Co: - are functions of the standard IO libc (glibc). - use an internal buffer (in their coding) - are formatted IO (with the "%.." parameter) for some of them. - use always the Linux buffer cache. - generally used for accessing bloc devices.

If you want more details here http://www.velocityreviews.com/forums/t437072-read-vs-fread.html

AIB