8

Is there an alternative to fsync for windows? (C++ builder)

Fsync required to include unistd.h and it's only for unix systems

Thanks!

user687459
  • 143
  • 5
  • 17

3 Answers3

2

The fflush function may do what you need, but it only applies to file handles.

Alternately, FlushFileBuffers may work for you, but it's Windows specific.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
  • What do you mean by "it only applies to file handles" ? If I used by file* and fopen so fflush will be enough? – user687459 Oct 14 '15 at 19:19
  • @user687459 - Correct, `fflush` is meant to work on `FILE *` types, so you should be good to go. – Mr. Llama Oct 14 '15 at 19:34
  • It doesn't work! The full story is that I write file of ~50MB and old file is also exists . After I write it, then I copy it to other location on PC but when I do the copy the new file is still doesn't updating so it copy the old file or corrupted file of the new version... Any ideas? – user687459 Oct 14 '15 at 20:19
  • 1
    So you're trying to keep two different files in sync across computers? That's not what `fsync` or `fflush` does at all. You might want to open a new question and include that specific information. – Mr. Llama Oct 14 '15 at 20:28
  • 1
    `fflush` flushes the program's I/O buffers to the kernel syscalls. It does _not_ emulate or call `fsync` or `FlushFileBuffers`, both of which make sure that the _kernel_ has written its buffers to disk. This is an important distinction. – Edward Thomson Dec 07 '17 at 12:15
2

From the man-page:

fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function.

The mentioned write function tells the operating system what the contents of the file should be. At this point all changes will be held in filesystem caches before actually being committed to disk.

The POSIX function fsync() tells the operating system to sync all changes from its caches to disk. As others have said you can use FlushFileBuffers on the Windows platform.

Ruud Althuizen
  • 558
  • 4
  • 10
  • fflush() has nothing to do with fsync() - they're very different buffers. fflush() flushes app-level buffers (which are lost in case of app crash) - and is relatively cheap, fsync() flushes OS-level buffers - which is usually necessary only if we have to consider OS crash too (!) - and is MUCH more expensive. – No-Bugs Hare May 21 '23 at 08:38
2

_commit looks about right, it takes a file descriptor just like fsync does:

The _commit function forces the operating system to write the file associated with fd to disk. This call ensures that the specified file is flushed immediately, not at the operating system's discretion.

James Clark
  • 1,765
  • 13
  • 17