I would strongly disagree with the claim that fopen
is prefered over open
. It's impossible to use fopen
safely when writing a file in a directory that's writable by other users due to symlink vulnerabilities/race conditions, since there is no O_EXCL
option. If you need to use stdio on POSIX systems, it's best to use open
and fdopen
rather than calling fopen
directly.
Now, as for locking it depends on what you want to do. POSIX does not have mandatory locking like Windows, but if you just want to ensure you're working with a new file and not clobbering an existing file or following a symlink, use the O_EXCL
and O_NOFOLLOW
options, as appropriate. If you want to do cooperative locking beyond the initial open, use fcntl
locks.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…