Fopen Vs Open

fopen() vs. open()

Short summary: fopen is buffered IO, open is unbuffered IO. Each has its flavours and its usage.

More:

  • fopen is buffered I/O. Buffering reduces the number of syscalls (open,read,write). Every syscall makes a transition from user to kernel and then to user level+ the time to get the read answer.
  • Open() is unbuffered only with respect to user data (the application which you don't care about); it is still buffered by the UNIX buffer cache unless you specifically open() a raw character device (e.g. /dev/rdsk/c1t2d0) rather than a block device (/dev/dsk/c1t2d0) or a fully-cooked file (myfile.dat).
  • The goal of the buffering provided by the standard I/O library is to use the minimum number of read and write calls. (Recall Figure 3.5, where we showed the amount of CPU time required to perform I/O using various buffer sizes.) Also, it tries to do its buffering automatically for each I/O stream, obviating the need for the application to worry about it. Unfortunately, the single aspect of the standard I/O library that generates the most confusion is its buffering.

Source: Advanced Programming in the UNIX environment, 2nd edition

  • If you do pure random, unbuffered can be better.
  • If you read a text file line by line fread performs better and is easier to use

http://forums12.itrc.hp.com/service/forums/questionanswer.do?admit=109447627+1204278307761+28353475&threadId=1163635

Other interesting observation:

Using the character b as part of the type allows the standard I/O system to differentiate between a text file and a binary file. Since the UNIX kernel doesn't differentiate between these types of files, specifying the character b as part of the type has no effect.

Source: Advanced Programming in the UNIX environment, 2nd edition

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License