I'm porting a program that used stdio file facilities to use an std::ofstream instead. The original program uses fsync to force a file's buffers out to the disk. The fsync() is used because I'm writing a logging file, and want to ensure that data is written ASAP (i.e., before a crash). The log file is always open, until the program is terminated.

I cannot figure out how to force the flush to disk with ofstream. I've tried the flush() call, but that just flushes the program's buffers out into the file system's buffers, and does not guarantee that the data is physically written to disk. I can observe an LED that lights up when the write actually takes place,

How do I emulate fsync() with an ofstream?

Thanks.

I am not certain this is the best way but it seems to work.
Note that the disk buffer is also an issue.

ofstream Out("File.log");
// stuff
Out.flush();    // Necessary since you need to ensure that the
                      // data ends up in the buffer.
// Some versions of stdlib have called this with the flush.  
Out.rdbud()->pubsync(); 
// What happens now is OS dependent.

crazyness but

fsync(fileObject.rdbuf())

would it not be something silly like that?

EDIT: Nevermind previous was a much better answer[/EDIT]

Referencing:
http://www.cplusplus.com/reference/iostream/ostream/flush.html

According to flush(), it already calls pubsync.

I tried it anyway:

pMyStream->rdbuf()->pubsync();

but it didn't help flush the output to disk. I had to wait for the system disk cache to flush it 30 seconds later.

The other suggesting of using:

fsync(fileObject.rdbuf());

doesn't work because rdbuf isn't a file number. That's an interesting idea, though, so if I can find the underlying file number (if it exists), then I can make that suggestion work.

Sorry, I'm a newbie on the formatting. Here it goes again...

Referencing:
http://www.cplusplus.com/reference/i...eam/flush.html

According to flush(), it already calls pubsync.

I tried it anyway:

pMyStream->rdbuf()->pubsync();

but it didn't help flush the output to disk. I had to wait for the system disk cache to flush it 30 seconds later.

The other suggesting of using:

fsync(fileObject.rdbuf());

doesn't work because rdbuf isn't a file number. That's an interesting idea, though, so if I can find the underlying file number (if it exists), then I can make that suggestion work.

it's code=c++ btw no need for language, I wasn't exactly sure what fsync() required. But i had a feeling that it would give you ideas.

I did say it was crazy XD

15 min edit grace period use it please.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.