Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of fopen vs stat

Tags:

c

file-io

fopen

I'm writing several C programs for an embedded system where every bit of performance we can squeeze out will matter. Part of that is accessing log files. When determining if a file exists, is there any performance difference between using open / fopen, and stat ? I've been using stat on the assumption that it only has to do a quick check against the file system, whereas fopen would have to actually gain access to a file and manipulate internal data structures before returning. Is there any merit to this ?

like image 970
Alex Marshall Avatar asked Nov 24 '25 15:11

Alex Marshall


1 Answers

stat is probably better, since it doesn't have to allocate resources for actually reading the file. You won't have to call fclose to release those resources, and you may also benefit from caching of recently checked files.

When it doubt, test it out. Time a big loop that checks for 1000 files using each method, with the appropriate mix of filenames that exist and don't exist.

If you have the source code for stat and fopen, you should be able to read through it and get an idea as to which will require more resources.

like image 80
tomlogic Avatar answered Nov 26 '25 06:11

tomlogic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!