2

For example, in C, we have fopen, and in Unix, we have open. There are some subtle differences between them, but they are doing the same thing.

There are also many other functions that both existing in C and Unix, what is the relationship between them? Which one should I prefer?

yuanqili
  • 362
  • 2
  • 9
  • 2
    Basic difference, `C` is a language, `Unix` is OS. – Sourav Ghosh Mar 10 '15 at 10:19
  • If you are targetting Unix system, prefer standard library functions anyway. If the function is not available, prefer POSIX functions. If not available use your local SO function ... *and if not available write your own*. – pmg Mar 10 '15 at 10:19
  • 2
    [What's the difference between “C system calls” and “C library routines”?](http://stackoverflow.com/questions/572942/whats-the-difference-between-c-system-calls-and-c-library-routines) – David Ranieri Mar 10 '15 at 10:20
  • 1
    That was answered here: http://stackoverflow.com/questions/1658476/c-fopen-vs-open – ChristianMurschall Mar 10 '15 at 10:24

2 Answers2

3

fopen(3) is returning a FILE* on success, but open(2) is returning a file descriptor on success, so they are not doing the same (since not giving the same type).

However, on Linux, fopen is internally using the open system call (and some others too...).

<stdio.h> file handles are handling buffering. With system calls like open and read you'll better do your own buffering.

See also this & that and read Advanced Linux Programming & syscalls(2). Be aware that on Linux, from the user-land application point of view, a system call is essentially an atomic elementary operation (e.g. the SYSCALL or SYSENTER machine instruction).

Use strace(1) to find out which system calls are executed (by a given process or command).

On Linux, the libc is implementing standard functions (like fprintf ....) above system calls.

Many system calls don't have any libc counterpart (except their wrapper), e.g. poll(2)

Community
  • 1
  • 1
Basile Starynkevitch
  • 1
  • 16
  • 251
  • 479
3

open is a system call from Unix systems. fopen is the standard c function to open a file.

There's some advantages of using fopen rather than open.

  • It's mult-platform, as it's C standard, you can port your program to any platform with a C compiler.

  • It supports use of C standard functions, (i.e: fprintf, fscanf)

  • If you are handling with text files, those functions can deal with different new lines characters (Unix/Windows)

dfranca
  • 4,381
  • 2
  • 23
  • 49