2

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);
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Seshadri R
  • 1,192
  • 14
  • 24
  • 4
    It is not filesystem, but your code segfauls. Always use strncpy, instead of strcpy. Here you don't need either - just use std::string. – Igor R. Jul 02 '19 at 05:58

3 Answers3

3
  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.

nivpeled
  • 1,810
  • 5
  • 17
2

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)

1

Compiling with gcc 9.1.0 went through successfully without any qualms.

Seshadri R
  • 1,192
  • 14
  • 24