hey, im making a database program using standard c functions (fopen, fclose...) and i need to read and write data to files quite frequently, so is it better to open (fopen) and close (fclose) the files before and after each operation or open the files at the beginning of the program and close them on exit? Will many open file handles affect the performance? thanks.

>>so is it better to open (fopen) and close (fclose) the files before and after each operation or open the files at the beginning of the program and close them on exit?

my openion is if you don't access files regularly then then open it and close it.
In linux(possibly on Windows too) there is something called file cache that is
maintained by the kernel. But you can open a file synchronously where as just after
a write operation it will be written to the file
use O_SYNC flag up.

>>Will many open file handles affect the performance? thanks.
Why not? The kernel maintains a internal data-structure to every file that we
opened.the integer file descriptor is just an index to that huge data-structure.
so the answer is yes.
If you program open lots of files, your program will be kicked by process manager
to protect system stability too.

When you feel you need to to synchronized IO then open the file in synchronized mode.

When the application exits normally the kernel will close the file handlers, but if
it exists abnormally you can't you can't gurantee the integrity of your data on
buffers are saved to the physical files.So it's always a better practice to invoke
close(fd) as soon as you finish with the file.Or open files in synchronous mode,
by that , kernel won't use the cache and it will be a performance problem too.

so it's up to to select what are the tradeoff's and what I should give up?

No way. Unless your code cannot exit abruptly (memory /file exceptions) do not even think of closing the file upon exit.

That`s just way too unsafe.

This article has been dead for over six months. Start a new discussion instead.