As for the global file descriptor, is that bad?

Suppose that in my program there are several functions that need to add data to a specific file. I open the file at the beginning of the program with a global file descriptor, so I can add it to where I need it. (Note that I know that I can pass a file descriptor as an argument to a function, but that is not the purpose of this question). It is incorrect to open the file descriptor at the beginning of the program, and then close it at the end; or is it better to have the function say void AppendFile(char *data_to_append);and then open the file and add to it and close it in the same function? If the program dies, FD will still be used, this is the only bad thing that I see, but at the same time, you open and close the same file hundreds and hundreds of times if you use this function.

+3
source share
7 answers

You are probably best off doing one open and only close. Opening / closing without stops will lead to a large number of lost EUTs.

You probably want to protect this function, but using a mutex so that only one stream can write to the file descriptor at a time.

Be sure to close your file, though in the end.

+2
source

If your program is single-threaded, everything is fine. If he dies while opening the file descriptor, it can still be closed by the operating system. If this is not the case, what guarantee will it not die inside your AppendFile function?

AppendFile. , , fwrite() s.

+1

, , . , , ( , ) . , . , .

, open/append/close - IMO, AppendFile , .

, , - - . AppendFile - , , . , .

+1

, :)

SQLite (http://www.sqlite.org/).

SQLite Oracle, fopen()

+1

. .

, void AppendFile(char *data_to_append);, AppendFile , , .

/ vaste, .

, , ( , ), , .

+1

.

, , , - . FD, , , - . ? ? - , ?

0

FILE *, , , stdio POSIX.

, , write ( ), .

, .

, , , stdio FILE * AppendFile - , FILE * , , .

A similar thing can happen with os file descriptors (integers returned by open), since different calls openwill create different file descriptors rather than sharing their search position, as the file has grown, different file descriptors will end from the search position, which in fact weren’t at the end of the file, if you can’t open the file only in add ( O_APPEND) mode , where the OS processes this for you.

Opening and closing a file over and over again creates a lot of extra work anyway.

0
source

Source: https://habr.com/ru/post/1764941/


All Articles