skr
skr

Reputation: 944

The os.path equivalent in C++ without Qt?

I need to set a directory and then read all the filenames of the files inside and store the whole path in a variable. I need to use this this variable later , to open the file and read it. I don't want use QDir for this. I saw the second answer to the question here. I can use boost/filesystem.hpp (I believe this need not be downloaded separately). But the problem is execution will look like this:

$ g++ -o test test.cpp -lboost_filesystem -lboost_system
$ ./test  

My first line, for creating executable object is already complicated due to OpenCV libraries and I don't want to add to it. I want to keep them simple (the following line plus whatever OpenCV wants):

g++ -o test test.cpp 

Is there any way to do it?

This is the python code for which I want to write C++ code:

root_dir = 'abc'
img_dir = os.path.join(root_dir,'subimages')

img_files = os.listdir(img_dir)
for files in img_files:
    img_name = os.path.join (img_dir,files)
    img = cv2.imread(img_name)

Upvotes: 2

Views: 3005

Answers (2)

For Linux or POSIX ....

You might use low-level nftw(3) or opendir(3) & readdir(3) etc... Of course you'll need to deal with dirty details (skipping . & .. entries, assembling the file path from the entry and the directory path, handling errors, etc...). You might also need stat(2). You should read Advanced Linux Programming & syscalls(2) to get a broader view.

For other OSes (notably Windows) you need other low-level functions.

BTW, you could look into the source code of Qt for QDir

You could consider also using POCO

Upvotes: 1

Pyrce
Pyrce

Reputation: 8596

Your choices are to use boost, QDir, roll your own, or use a newer compiler which has adopted some of the TR2 features that are staged for C++17. Below is a sample which roughly should iterate over files in a system agnostic manner with the C++17 feature.

#include <filesystem>
namespace fs = std::experimental::filesystem;
...
fs::directory_iterator end_iter;
fs::path subdir = fs::dir("abc") / fs::dir("subimages");
std::vector<std::string> files;

for (fs::directory_iterator dir_iter(subdir); dir_iter != end_iter; dir_iter++) {
  if (fs::is_regular_file(dir_iter->status())) {
    files.insert(*dir_iter);
  }
}

Upvotes: 3

Related Questions