-2

It is understood that fread() is a library function and buffered I/o operation. read() is a system call which is unbuffered I/o. As buffered I/o is faster fread can be advantageous. But fread finally calls read() for the operation. Then how fread() is advantageous than read() ? Why fread() is needed whereas read can do the job ?

SKM
  • 29
  • 2
  • 4
  • 1
    this might help you: http://stackoverflow.com/questions/584142/what-is-the-difference-between-read-and-fread – bianconero Sep 16 '14 at 13:13
  • 1
    `read` is a system call which may not be portable, while `fread` being std C is portable. – Mohit Jain Sep 16 '14 at 13:24
  • Currently this is marked as duplicate but IMHO there's a slight difference between "Whats the difference?" and "Which one is better?". The answers of the linked question don't give any helpful information in terms of performance, portability and safety. – MarcusS Jul 21 '22 at 07:33

1 Answers1

1

If you don't need raw access on system level you should use the buffered library functions.

fread is part of the stdio.h C-Header. If you want to write portable code for Windows, Linux and Mac this is the best way to do it because the function is available on every C-Compiler.

code monkey
  • 2,094
  • 3
  • 23
  • 26
  • fread() subsequently calls read() internally to get the data into the buffer, right??? Then Why to use fread and not read() directly? – SKM Sep 17 '14 at 08:17
  • That's wrong. It depends which system you are using. On Linux/ Unix `fread()` calls `read()`. However the `read()` system call is POSIX. Windows is not POSIX and on Windows there is no `read()` function. On Windows systems `fread()` calls anoother function. (I don't know the name because I don't know the Windows API). In addition `fread()` is easier to use. – code monkey Sep 17 '14 at 08:23
  • Yes I got some point like, There are some situations where The file is read very often. In those situations, if read() is used, then kernel switch is very frequent which is not good. To avoid that situation fread can be used. As fread is buffered I/O, in the first call it internally calls read and copies the whole block in the buffer cache. Now the subsequent call to fread will refer the data already in buffer cache(no need to call read() again). Hence Its advisable to use fread() in this type of situations. – SKM Sep 18 '14 at 08:59