我有一个 C++ 程序正在写入 Windows 7 上的文件。当我调用 f.flush()
时,NTFS 文件没有变大。有什么办法可以强制刷新文件吗?
最佳答案
你可以看这里:
How do I get the file HANDLE from the fopen FILE structure?
代码如下所示:
FlushFileBuffers((HANDLE) _fileno(_file));
不要忘记在调用 FlusFileBuffers 之前调用 fflush(file)。
对于 std::fstream 和 gnu STL,我在我的 linux box 上检查过,家里没有 window , 但应该与 mingw 一起使用,可能需要一些修改:
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <fstream>
#include <ext/stdio_filebuf.h>
int main(int argc, char *argv[])
{
assert(argc == 2);
std::ifstream f(argv[1]);
assert(!!f);
/*
//cin, cout etc
__gnu_cxx::stdio_filebuf<char> *stdio_buf = dynamic_cast<__gnu_cxx::stdio_filebuf<char> *>(f.rdbuf());
if (stdio_buf != 0) {
printf("your fd is %d\n", stdio_buf->fd());
return EXIT_SUCCESS;
}
*/
std::basic_filebuf<char> *file_buf = dynamic_cast<std::basic_filebuf<char> *>(f.rdbuf());
if (file_buf != 0) {
struct to_get_protected_member : public std::basic_filebuf<char> {
int fd() { return _M_file.fd(); }
};
printf("your fd is %d\n", static_cast<to_get_protected_member *>(file_buf)->fd());
}
printf("what is going on?\n");
return EXIT_FAILURE;
}
关于c++ - 如何在 win32 上刷新 stdlib 输出文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107436/