Force ofstream file flush on Windows

2019-07-21 18:04发布

I'm using an ofstream to write data to a file. I regularly call flush on the file but the backing file doesn't always get updated at that time. I assume this is related to an OS-level cache, or something inside the MSVC libraries.

I need a way to have the data properly flush at that point. Preferably written to disc, but at least enough such that a copy operation from another program would see all data up to the flush point.

What API can I use to do this?

4条回答
smile是对你的礼貌
2楼-- · 2019-07-21 18:27

FlushFileBuffers will flush the Windows write file cache and write it to a file. Be aware it can be very slow if called repeatedly.

I also found this KB article which describes the use of _commit(). This might be more useful to you since you are using ofstream.

CXXFileBuf.flush();
_commit(CXXFileBuf.rdbuf()->fd());
查看更多
一夜七次
3楼-- · 2019-07-21 18:29

Just add commode.obj to Linker->Input->Additional Dependencies in the project's Property Pages in Visual Studio and call std::ostream::flush(). That way std::ostream's flush will link against another method which has the desired behavior. That's what helped to me.

查看更多
做个烂人
4楼-- · 2019-07-21 18:38

If this is a windows-only solution, you might want to use FlushFileBuffers(). This means you will have to re-write some of your code to accomodate calls to CreateFile(), WriteFile(), etc. If your application depends on many different operator<< functions, you can write your own std::streambuf.

You also might want to read the remarks section carefully. In particular,

Due to disk caching interactions within the system, the FlushFileBuffers function can be inefficient when used after every write to a disk drive device when many writes are being performed separately. If an application is performing multiple writes to disk and also needs to ensure critical data is written to persistent media, the application should use unbuffered I/O instead of frequently calling FlushFileBuffers.

查看更多
祖国的老花朵
5楼-- · 2019-07-21 18:45

I used:

MyOfstreamObject.rdbuf()->pubsync();

I'm using stl_port on Win 7 with ICC 9.1.

I have not tested the solution extensively but it seems to work... Maybe it could solve the problem of the absence of fd() noticed by edA-qa mort-ora-y .

查看更多
登录 后发表回答