Lets say there are multiple functions throughout my program that need to append data to a certain file. I open the file at the beginning of the program with a global file handle so I can append to it wherever I need to. (Note that I know I could pass the file handle as an argument to the functions but that is not the purpose of this question). Is it bad to open the file handle at the beginning of a program, and then close it at the end; or is it better to have a function say void AppendFile(char *data_to_append); and then open the file and append to it and close it in this same function? If the program dies the FD would still be in use is the only bad thing I see, but at the same time you are opening and closing the same file hundreds and hundreds of times if you use the function.
Lets say there are multiple functions throughout my program that need to append data
Share
You are probably best to do a single open and a single close. Opening/Closing non stop will lead to a lot of wasted IOs.
You will probably want to protect this function though with a mutex so only one thread can be writing to the file handle at a time.
Do make sure that you close your file though eventually.