Why should I use close () to close the file?

I am studying some file functions and therefore doubt it.

I wonder why you need to call close()to close the file? If I did not call close()after reading / writing a file, what could happen? And if I called close(), can I use a file descriptor?

+5
source share
6 answers
  • If the file has some kind of buffering behind it, and you do not call it close, you may lose data.

  • If the OS has limited resources (for example, the number of open files), then without closing the files, you lose system resources.

  • , ( )

+7

, , . , , , , .

. .

+2

close() , . , , ,

:

1) .
2) , , .
3) , FIFO, , .

+2

, write(), . close(), , . close() .

0

: , fclose().

fclose(ifp);
fclose(ofp);

, . , . , C, -, ,

fprintf(ofp, "Whatever!\n");

, . :

:

----------------------------------------------
| a | b  | c | W | h | a | t | e | v | e | r |
----------------------------------------------
| ! | \n |   |   |   |   |   |   |   |   |   |
----------------------------------------------
|   |    |   |   |   |   |   |   |   |   |   |
----------------------------------------------
|   |    |   |   |   |   |   |   |   |   |   |
----------------------------------------------
...

( , .)

( ), , , .

: http://www.cs.bu.edu/teaching/c/file-io/intro/

0
  • When you write to a file, you write first to the buffer, some function calls a flash, and the data is written to the file, but others simply write to the buffer. When the buffer is full, it is flushed to the file without calling the flash directly. You can also when you want, if you want to be sure.
  • And you cannot use the file descriptor after closing it.
0
source

All Articles