user1424739
user1424739

Reputation: 13655

Is seek to 0 in an opened file faster than close the file then open it again?

Suppose that I have a file opened already. I'd like to write some new content to it (overwriting any old content in the file). I want this operation to operate efficiently regardless of the size of the file.

Is seek to 0 in the already opened file faster than close the file then open it again?

Upvotes: 1

Views: 263

Answers (1)

Schwern
Schwern

Reputation: 164769

Before we talk about which is faster, first we must show they are equivalent. They're not.

Just seeking to 0 is insufficient to be sure all the content is overwritten. What if the new content is shorter? You must seek and truncate to be sure.

There's no standard way to truncate an open file. POSIX has ftruncate and Windows has SetEndOfFile. fopen(filename, "w") is standard C. So seek and truncate brings compatibility problems.

See Is there a guaranteed and safe way to truncate a file from ANSI C FILE pointer? and How to truncate a file in C?.


There is another subtle difference around file deletion. On Unix, if you delete a file any open file handles remain open. The data remains until all file handles are closed. This is commonly exploited to have secure temp files: open the temp file for both reading and writing, immediately delete the file, and continue to read and write to the open file handle. Invisible temp file.

Let's say your file is deleted while your filehandle is open. If you seek and truncate you're still working with the same data, but there's no file. If you fopen you're writing to a new file. This can have behavior and security implications.

There are similar issues with file renaming. If your file got renamed while the filehandle is open, seek and truncate will work with the renamed file (there are various non-portable ways to get the filename from a file handle). fopen will open a file with the old name.


Which is faster? Probably seek and truncate. fopen will have to do that anyway, plus the overhead of locating the data associated with the filename, checking permissions, etc...

You can benchmark this easily enough. You can also use strace, or the equivalent for your operating system, to look at the underlying system calls.

Upvotes: 2

Related Questions