简体   繁体   English

为什么 std::filesystem::file_size(file) 与实际文件大小不同?

[英]Why std::filesystem::file_size(file) is differnt with real file-size?

#include<iostream>
#include<random>
#include<fstream>
#include<filesystem>

int main(){
    std::default_random_engine dre;
    std::uniform_int_distribution<> uid{ 1, 100'000 };

    std::filesystem::path file("./test.txt");

    std::unique_ptr<int[]> D{ std::make_unique<int[]>(10'000) };
    for (int i = 0; i < 10'000; ++i)
        D[i] = uid(dre);

    std::ofstream out(file, std::ios::out | std::ios::binary);
    out.write((char*)D.get(), sizeof(int) * 10'000);

    std::cout << sizeof(int) * 10'000 << std::endl;
    std::cout << std::filesystem::file_size(file) << std::endl;
    // should be same.
}

I expected the result will be same.我预计结果会一样。 But the result is但结果是

40000
36864

When I checked the test.txt file in window, the size is 40'000.当我检查 window 中的test.txt文件时,大小为 40'000。 that is what I expected.这就是我的预期。 But while runtime, something I can't understand is happening.但是在运行时,我无法理解的事情正在发生。 why std::filesystem::file_size(file) is less than real file size?为什么std::filesystem::file_size(file)小于实际文件大小?

std::ofstream buffers its output, so it is possible (even likely) that by the time you are calling file_size() , there are still bytes in the buffer that ofstream has not written to the actual file yet. std::ofstream缓冲其 output,因此有可能(甚至很可能)当您调用file_size()时,缓冲区中仍有字节ofstream尚未写入实际文件。

Close the ofstream first:先关闭ofstream

std::ofstream out(file, std::ios::out | std::ios::binary);
out.write((char*)D.get(), sizeof(int) * 10'000);
out.close();

std::cout << std::filesystem::file_size(file) << std::endl;

Or, at least call flush() on it:或者,至少在其上调用flush()

std::ofstream out(file, std::ios::out | std::ios::binary);
out.write((char*)D.get(), sizeof(int) * 10'000);
out.flush();

std::cout << std::filesystem::file_size(file) << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM