2

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)
Community
  • 1
  • 1
skr
  • 914
  • 3
  • 18
  • 35

2 Answers2

3

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);
  }
}
Pyrce
  • 8,296
  • 3
  • 31
  • 46
  • I think I will go with boost and create a file that contains everything that should be called while creating the object. What do you think of that? – skr Nov 01 '16 at 19:03
  • Sounds like the most reliable approach. In a few years there will be less need to carry such a large bundle into small problems like this. – Pyrce Nov 01 '16 at 20:00
1

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

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547