Как очистить выходной файл stdlib на win32? - PullRequest
1 голос
/ 13 ноября 2011

У меня есть программа C ++, которая пишет в файл в Windows 7. Когда я вызываю f.flush(), файл NTFS не увеличивается. Есть ли способ заставить файл очиститься?

Ответы [ 2 ]

2 голосов
/ 13 ноября 2011

Вы можете посмотреть здесь: Как получить файл HANDLE из структуры fopen FILE? код выглядит так:

 FlushFileBuffers((HANDLE) _fileno(_file));

не забудьте вызвать fflush (file), перед вызовом FlusFileBuffers.

Для std :: fstream и gnu stl, я проверил это на моем linux box, дома нет окон, но должен работать с 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;
}
0 голосов
/ 13 ноября 2011

flush очищает только внутренние буферы, хранящиеся в стандартном коде библиотеки.

Чтобы очистить буферы ОС, вам нужно / нужно вызвать FlushFileBuffers ( после вызова).f.flush()).

...