Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between fclose and close

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?

like image 745
Flash Avatar asked Oct 24 '13 11:10

Flash


People also ask

Does Fclose call close?

The fclose() function performs a close() on the file descriptor that is associated with the stream pointed to by stream. After the call to fclose(), any use of stream causes undefined behavior. Upon calling exit(), fclose() is performed automatically for all open files.

What does Fclose mean?

fclose() — Close Stream The fclose() function closes a stream pointed to by stream . This function deletes all buffers that are associated with the stream before closing it. When it closes the stream, the function releases any buffers that the system reserved.

Does Fclose close FD?

The fclose() function flushes the stream pointed to by stream (writing any buffered output data using fflush(3)) and closes the underlying file descriptor.

What is the difference between fopen () and fclose ()?

The fopen() function is used to open the file or an URL. The fclose() function closes the opened file.


1 Answers

fclose() is function related with file streams. When you open file with the help of fopen() and assign stream to FILE *ptr. Then you will use fclose() to close the opened file.

close() is a function related with file descriptors. When you open file with the help of open() and assign descriptor to int fd. Then you will use close() to close the opened file.

The functions like fopen(), fclose() etc are C standard functions, while the other category of open(), close() etc are POSIX-specific. This means that code written with open(), close() etc is not a standard C code and hence non-portable. Whereas the code written with fopen(), fclose etc is a standard code and can be ported on any type of system.

which one should I use?

It depends on how you opened the file. If you open a file with fopen(), you should use fclose() and if you open file with open(), you should use close().

If forked children have access to the file as well, what should they do when they are finished with the file?

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 and man close

like image 64
Gangadhar Avatar answered Oct 09 '22 06:10

Gangadhar