How to get the file size in bytes with C++17

前端 未结 2 853
别那么骄傲
别那么骄傲 2021-02-01 11:52

Are there pitfalls for specific operating systems, I should know of?

There are many duplicates (1, 2, 3, 4, 5) of this question but they were answered decades ago. The v

2条回答
  •  借酒劲吻你
    2021-02-01 12:05

    (added in C++17) makes this very straightforward.

    #include 
    #include 
    
    // ...
    
    std::uintmax_t size = std::filesystem::file_size("c:\\foo\\bar.txt");
    

    As noted in comments, if you're planning to use this function to decide how many bytes to read from the file, keep in mind that...

    ...unless the file is exclusively opened by you, its size can be changed between the time you ask for it and the time you try to read data from it.
    – Nicol Bolas

提交回复
热议问题