【问题标题】:How do I flush a stdlib output file on win32?如何在 win32 上刷新 stdlib 输出文件?
【发布时间】:2011-11-12 20:41:57
【问题描述】:

我有一个在 Windows 7 上写入文件的 C++ 程序。当我调用 f.flush() 时,NTFS 文件没有变大。有没有办法强制刷新文件?

【问题讨论】:

  • 您确定有待处理的输出吗?另外,fsync(或 [_commit]())是你的朋友(archives.postgresql.org/pgsql-hackers-win32/2003-11/…
  • 哦,是的,我很肯定有输出。它不是待处理的——它已被发送。但 NTFS 缓冲区。
  • 这是一个繁重的 CRT 实现细节。对于 MSVC CRT,它是通过将 'c' (= commit) 传递给 fopen() mode 参数来完成的。查看您使用的那个的来源。

标签: c++ windows flush std


【解决方案1】:

你可以看这里:
How do I get the file HANDLE from the fopen FILE structure?
代码如下所示:

 FlushFileBuffers((HANDLE) _fileno(_file));

在调用 FlusFileBuffers 之前不要忘记调用 fflush(file)。

对于 std::fstream 和 gnu stl,我在我的 linux 机器上检查过,家里没有窗户, 但应该与 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 FILE* 对象,而不是 C++ iostream 对象。
  • 这个比较难,在VS10自带的库中,你可以从FILE构造std::fstream对象,在其他一些库上,我看到std::fstream::fd方法,到文件描述符来自 std::fstream。你用什么编译器?
  • 我使用 mingw 作为 Fedora Core 的交叉编译器。所以我使用的是 GNU STL。
  • 我没有找到f.fd() 方法。
  • 更新我的答案,包括我之前用于获取文件句柄的代码。
【解决方案2】:

flush 只刷新标准库代码保存的内部缓冲区。

要刷新操作系统的缓冲区,您需要/想要调用FlushFileBuffers调用f.flush()之后)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-04-09
  • 2018-11-07
  • 1970-01-01
  • 2017-09-24
  • 2020-10-05
  • 1970-01-01
  • 2017-09-08
  • 2022-01-25
相关资源
最近更新 更多