Syamprasad K R Syamprasad K R - 1 month ago 14
C++ Question

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)

Answer

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);
  }
}