If I fopen
a file, what's the difference between calling fclose
or close
and which one should I use?
If forked children have access to the file as well, what should they do when they are finished with the file?
If I fopen
a file, what's the difference between calling fclose
or close
and which one should I use?
If forked children have access to the file as well, what should they do when they are finished with the file?
As for your second question, forked children have the same numeric file descriptor as the parent, but it's a copy; they can close it, and it will still be open for the parent and other children. (Though personally, I don't like to have files open when I
fork()
... I like to make that sort of shared resource usage explicit. Pipes, of course, are an exception.)fclose()
is function related with file streams. When you open file with the help offopen()
and assign stream toFILE *ptr
. Then you will usefclose()
to close the opened file.close()
is a function related with file descriptors. When you open file with the help ofopen()
and assign descriptor toint fd
. Then you will useclose()
to close the opened file.The functions like
fopen()
,fclose()
etc are C standard functions, while the other category ofopen()
,close()
etc are POSIX-specific. This means that code written withopen()
,close()
etc is not a standard C code and hence non-portable. Whereas the code written withfopen()
,fclose
etc is a standard code and can be ported on any type of system.It depends on how you opened the file. If you open a file with
fopen()
, you should usefclose()
and if you open file withopen()
, you should useclose()
.This is also dependent on where you made the
fork()
call: before opening the file or after opening it.See: Are file descriptors shared when fork()ing?
See:
man fclose
andman close
If you open a file with
fopen
, close it withfclose
. Usingclose
in this case may cause a memory leak on a handle allocated byfopen
open()
andclose()
are UNIX syscalls which return and take file descriptors, for use with other UNIX syscalls such aswrite()
.fopen()
andfclose()
are standard C library functions which operate onFILE*
s, for use with things likefwrite
andfprintf
. The latter are almost always what you should be using: They're simpler and more cross-platform.