C fopen vs open

Asked 1 years ago, Updated 1 years ago, 137 views

I learned both in Linux class, but open is only on the test and I've never actually used it.

You can open both files, but even if you look at other codes, they only use fopen files. Why is that?

file-io c linux unit

2022-09-22 22:18

2 Answers

Fopen is used more often than open for the following reasons.

Usually, fopen() is preferred for reasons 1 and 2.

But buffered-IO can produce unexpected results (especially multipithreading and seek, etc Make sure to use the appropriate amount of fflush() and use fclose() at the end


2022-09-22 22:18

open is the system call of the operating system that follows POSIX fopen is a standard function of the compiler to follow ANSI-C.

Open is compatible with the POSIX specification; not all operating systems comply with the POSIX specification. fopen is compatible with ANSI-C specification. Most C compilers tend to follow ANSI-C standards. Therefore, fopen is better in terms of compatibility.

For the implementation of fopen, the open or counterpart provided by the operating system internally calls the system call. Therefore, contrary to what @Park Dan-yeop said, it is difficult to say that fopen is faster than open. (There is room for misunderstanding in this part, so I added an answer.) @Park Danyeob, please don't be offended )

))

Finally, you can think of open as a low-level API, and fopen as a high-level API (convenient for programmers). Considering compatibility, it would be better to use fopen, and to improve the performance of I/O such as buffer management, it would be better to use open directly.


2022-09-22 22:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.