How to get file size using C++17 filesystem library

To get the filesize (in bytes) of any file (test.xml in our example) using only the C++17 filesystem library, use this snippet:

New version usingĀ filesystem:

#include <filesystem>
#include <iostream>

using namespace std;
using namespace std::filesystem;

int main() {
    size_t filesize = file_size("test.xml");
    cout << filesize << endl;
}

Old version usingĀ experimental/filesystem

#include <experimental/filesystem>
#include <iostream>

using namespace std;
using namespace std::experimental::filesystem;

int main() {
    size_t filesize = file_size("test.xml");
    cout << filesize << endl;
}

With GCC/G++ you need to link the stdc++fs library, i.e. compile like this:

g++ -o test test.cpp -lstdc++fs