F. T. D. C.
F. T. D. C.

Reputation: 47

Why isn't it a good idea to open the file before each writing and close it right after each writing?

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

Answers (2)

Govind Parmar
Govind Parmar

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

Mike Nakis
Mike Nakis

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:

  1. It is terribly inefficient.
  2. It requires an extra seek to the end of file in order to append.
  3. It forfeits atomicity, meaning that the file may be renamed, moved, deleted, written to, or locked by someone else between the write operations.

Upvotes: 5

Related Questions