Reputation: 47
Suppose you are writing a list of names in a file, each name being written in a write command. Why isn't it a good idea to open the file before each writing and close it right after each writing?
Intuitively, I would say that this aproach is a lot more time consuming than writing to a buffer and posteriorly writing to the file. But I'm sure there is a better explanation to that. Can someone enlight me?
Upvotes: 3
Views: 128
Reputation: 21542
Think of all the possible reasons why fopen
(and related) might fail when you call it even once: the file doesn't exist, your account doesn't have permission to access or create it, another program is using the file exclusively, etc.
If you are repeatedly opening and closing the file for every write operation, this chance of failure increases quite a bit.
Also, there is an overhead associated with acquiring and releasing resources (e.g. files). You'd observe it more if you were acquiring and releasing write access to the file every single time you needed to write.
Upvotes: 1
Reputation: 61986
Let's sum it up:
Opening and closing a file for every single write operation, when many such operations are planned, is a bad idea because:
Upvotes: 5