I have a small program written in C++ with Win32 that writes data to the slack space of a file; it does this by writing to the data to the file with WriteFile() and then shrinking the file with SetEndOfFile() to leave the original file in tact, but still have the written data remain on disk. By examining my hard drive with Winhex, I've confirmed that this approach works, but only in rather unusual circumstances.
Basically, whenever I run my program normally, either by itself or in the Visual Studio debugger, I can't see any changes in the data on the disk after it finishes; Windows confirms that the file itself was modified, but Winhex doesn't show the new slack space data I wrote. However, if I start the program in the debugger with a breakpoint right after my call to WriteFile(), when the breakpoint is hit, I can see the changes on the hard drive in Winhex immediately. I figured that the buffered data to write wasn't getting flushed out in time, so I put in a call to FlushFileBuffers() right after WriteFile(), but I was still getting the same behavior. However, by putting in other meaningless calls to take up time, like a call to system("pause") after WriteFile(), the program successfully wrote the data to disk no matter how I ran it.
So, does anyone know what's really going on here? How can I ensure (without using hacks like system("pause")) that my program always writes its data to disk? Any help would be appreciated.
The code in question (that requires a breakpoint on the call to SetFilePointer()) is attached.
SetFilePointer(current_file, 0, NULL, FILE_END);
for (int i = 0; i < cluster_size / 2; ++i)
WriteFile(current_file, "01", 2, &bytes_returned, NULL);
SetFilePointer(current_file, -cluster_size, NULL, FILE_END);