Is there any ordinary reason to use open() instead of fopen()?

前端 未结 7 1326
南旧
南旧 2021-01-05 13:05

I\'m doing a small project in C after quite a long time away from it. These happen to include some file handling. I noticed in various documentation that there are functions

7条回答
  •  爱一瞬间的悲伤
    2021-01-05 13:32

    The objection that "fopen" is portable and "open" isn't is bogus.

    fopen is part of libc, open is a POSIX system call.

    Each is as portable as the place they come from.

    i/o to fopen'ed files is (you must assume it may be, and for practical purposes, it is) buffered by libc, file descriptors open()'ed are not buffered by libc (they may well be, and usually are buffered in the filesystem -- but not everything you open() is a file on a filesystem.

    What's the point of fopen'ing, for example, a device node like /dev/sg0, say, or /dev/tty0... What are you going to do? You're going to do an ioctl on a FILE *? Good luck with that.

    Maybe you want to open with some flags like O_DIRECT -- makes no sense with fopen().

提交回复
热议问题