C++17 filesystem call generates segmentation fault

Viewed 1422

Based on the response to Size of file using C++17, I wrote the following program. But, when the executable is run, I get a segmentation fault. I am using g++ 8.3.0 on an iMac running High Sierra.

// c17filesize.cpp
// Jul-02-2019

#include <cstring>
#include <filesystem>
using namespace std;

int main(int argc, char **argv)
{
    char filename[100];
    (argc > 1) ? strcpy(filename, argv[1]) : strcpy(filename, __FILE__);
    auto size = filesystem::file_size(filename);
}
3 Answers
  1. Prefer using string (and its contructor) over c style strings.
  2. according https://en.cppreference.com/w/cpp/filesystem/file_size you must specify full path. Did you verify argv[1] holds a full path?
  3. check the file exist before attempting to read its size std::filesystem::exists(filename);

  4. use try and catch sections to catch an exception.

Just bumped into segfault whilst using std::filesystem:exists.

With GCC 8.3. Had to link with -lstdc++fs to solve the problem.

Note: GCC 9+ solves this problem (https://gcc.gnu.org/gcc-9/changes.html)

Compiling with gcc 9.1.0 went through successfully without any qualms.

Related