Search code examples
c++xcodeclangc++17std-filesystem

c++ 17 filesystem::recursive_directory_iterator() gives error no such directory on mac but works on windows


Configurations

  • macOS: 10.15.5
  • xcode: 11.5
  • clang: 11.0.3
  • Project is set to c++17

I am new to macOS and trying to solve a simple problem..

#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = std::filesystem;

int main(int argc, const char * argv[]) {
    for(const auto& p: fs::recursive_directory_iterator("data/"))
        cout << p.path() << '\n';
    return 0;
}

This code gives me error (tried on xcode, clion and cmake) -

uncaught exception of type std::__1::__fs::filesystem::filesystem_error: 
filesystem error: in recursive_directory_iterator: No such file or directory [data/]

ISSUE
Here data folder is created by me manually or some time automatically. Random files will be generated in it (sub directories files too), I need path and name of all those files.

ADDITIONAL INFORMATION
This code works perfectly fine

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    fs::create_symlink("a", "sandbox/syma");
    for(auto& p: fs::recursive_directory_iterator("sandbox"))
        std::cout << p.path() << '\n';
    fs::remove_all("sandbox");
}

Solution

  • I see three options:

    1. In XCode, go to Product - Scheme - Edit Scheme, then choose the Run target in the left column, switch to Options and use the Working directory to point to the directory in which you want the target executable to be run. This is where your data directory must exist for the program to succeed.

    2. Figure out the actual working directory XCode is using. Create the data directory there.

    3. Specify an absolute path, as in

      for(const auto& p: fs::recursive_directory_iterator("/my/absolute/path/data/"))
      

    The difference to the working snippet that you posted is that it creates a new directory relative to XCode's working directory. Which can then obviously be found, contrary to the manually created data directory next to main.cpp.