Ynv
Ynv

Reputation: 1974

Do I need to fflush or close a file before calling stat on it?

After opening a file for writing:

FILE *file = fopen("./file", "w");

Can I assume the file was created immediately? Is it safe to call:

 stat( "./file", info);

Or should I better:

 fflush(file);

or

 fclose(file);

beforehand?

Edit: Assume non NULL file after fopen call

Upvotes: 2

Views: 1292

Answers (3)

Pavan Manjunath
Pavan Manjunath

Reputation: 28545

If the call to fopen is successful then it means that the file is created. The file may not be committed ( flushed ) to the disk though. But you need not worry about this as the next call to stat will fetch the file from the kernel buffer.

So an fflush or an fclose is not required in this particular case.

The few times where in you need to scratch your head about flushing to disk is when there is a probability of a system crash. In this case if you haven't committed data completely to the disk using something like fsync, then there might be probable data loss upon next system restart.

Upvotes: 1

tuxuday
tuxuday

Reputation: 3037

Yes, logically we could do it. As opening a file for writing in read-only filesystem fails. This indicates that fopen()/open() does required checks. Other way to confirm is this by opening file with x similar to O_EXCL flag of open().

Upvotes: 1

codaddict
codaddict

Reputation: 455350

The fopen manual page says:

If mode is w, wb, a, ab, w+, wb+, w+b, a+, ab+, or a+b, and the file did not previously exist, upon successful completion, the fopen() function shall mark for update the st_atime, st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.

So I think it is safe to stat on the file just after a successful fopen call.

Upvotes: 2

Related Questions