100

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 very high voted answers in many of these questions are wrong today.

Methods from other (old QA's) on .sx

  • stat.h (wrapper sprintstatf), uses syscall

  • tellg(), returns per definition a position but not necessarily bytes. The return type is not int.

9
  • 4
    Starter for 10: en.cppreference.com/w/cpp/header/filesystem Jun 30, 2019 at 20:36
  • 5
    @L.F.: Well, the first question has been closed as a duplicate of the second, which explains why the accepted answer in the first is wrong. The third one is asking about similar tellg problems. The only one worth bothering with is the fourth one, and that one's not great, since it talks too much about ofstream, in both the question and its answers. This one is far better at expressing the intent than the others (except for the first, which is oddly closed). Jul 1, 2019 at 5:06
  • 6
    Please stop adding irrelevant information to your question and the question title. The year is irrelevant; the technologies are relevant.
    – elixenide
    Jul 1, 2019 at 21:08
  • 2
    What's wrong with stat(2) anyways? Has it grown too old or what? Jul 2, 2019 at 12:11
  • 1
    @LorinczyZsigmond What's wrong with stat(2) It's not part of the language standard. Jul 2, 2019 at 13:31

2 Answers 2

136

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

#include <cstdint>
#include <filesystem>

// ...

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

23
  • 12
    Little offtopic: is there a world where std::uintmax_t will be able to hold greater values than std::size_t? If not, why not use std::size_t, which arguably is more recognisable? +1 on the answer, btw
    – Fureeish
    Jun 30, 2019 at 20:39
  • 14
    @Fureeish I used just because that's the type file_size returns. Looks slightly weird to me too. Jun 30, 2019 at 20:40
  • 42
    @Fureeish std::size_t is only required to hold the max size of in memory objects. Files can be considerably larger, Jun 30, 2019 at 20:42
  • 29
    @Fureeish Well, on 32-bit Windows (and I assume on most modern 32-bit platforms) size_t is 32 bits, and uintmax_t is 64 bits. Jun 30, 2019 at 20:43
  • 16
    @HolyBlackCat: It would be good to say something about the fact that the filesystem is global, and thus 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. Jul 1, 2019 at 4:59
31

C++17 brings std::filesystem which streamlines a lot of tasks on files and directories. Not only you can quickly get file size, its attributes, but also create new directories, iterate through files, work with path objects.

The new library gives us two functions that we can use:

std::uintmax_t std::filesystem::file_size( const std::filesystem::path& p );

std::uintmax_t std::filesystem::directory_entry::file_size() const;

The first function is a free function in std::filesystem, the second one is a method in directory_entry.

Each method also has an overload, as it can throw an exception or return an error code (through an output parameter). Below is the detail code explaining all the possible cases.

#include <chrono>
#include <filesystem>  
#include <iostream>

namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
    try
    {
        const auto fsize = fs::file_size("a.out");
        std::cout << fsize << '\n';
    }
    catch (const fs::filesystem_error& err)
    {
        std::cerr << "filesystem error! " << err.what() << '\n';
        if (!err.path1().empty())
            std::cerr << "path1: " << err.path1().string() << '\n';
        if (!err.path2().empty())
            std::cerr << "path2: " << err.path2().string() << '\n';
    }
    catch (const std::exception& ex)
    {
        std::cerr << "general exception: " << ex.what() << '\n';
    }

    // using error_code
    std::error_code ec{};
    auto size = std::filesystem::file_size("a.out", ec);
    if (ec == std::error_code{})
        std::cout << "size: " << size << '\n';
    else
        std::cout << "error when accessing test file, size is: " 
              << size << " message: " << ec.message() << '\n';
}
2
  • 2
    What exactly is "this"? Can you explain what all this code is used for, especially when the accepted answer uses much less code?
    – Nico Haase
    Jul 2, 2019 at 15:24
  • The accepted answer ignores exceptions, which can be thrown when the file doesn't exist, which is pretty common.
    – Robert
    Nov 26, 2022 at 5:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.