'Retrieving sub directory name and using it to call function in linux . Every time calling fun1 with the same sub directory name
Suppose inside main directory (A) i have only 2 sub directories B and C:
A:
-B
-C
I want to achieve following functionality:
Calling getLangDir function the first time, then I should be able to call
fun1(0, A)only if I calledgetLangDirfunction for the second time, then I should be able to callfun1(1,B)only.
In fun1 I am using foldernum value and entity->d_name string.
Here in first and second case I am calling like fun1(0,A), fun1(1,A) respectively.
NOTE : Here Using dirent header file. Also not call getLangDir recursively as I want first level subdirectory .
int foldernum=0; //global variable
void getLangDir(std::string dirname) {
DIR* dir = opendir(dirname.c_str());
if (dir == NULL) return;
std::cout<<"Reading directory in: "<< dirname<<std::endl;
struct dirent* entity;
entity = readdir(dir);
while (entity != NULL)
{
if (entity->d_type == DT_DIR && strcmp(entity->d_name, ".") != 0 && strcmp(entity->d_name, "..") != 0)
{
if(foldernum==0){
std::string str(entity->d_name);
fun1(foldernum,str);
foldernum++;
break;
}
else if(foldernum==1){
std::string str(entity->d_name);
fun1(foldernum,str);
foldernum++;
break;
}
else
return;
}
entity = readdir(dir);
}
closedir(dir);
}
Solution 1:[1]
I think I understand what you want.
Your overall approach is wrong because maintaining state of functions using global variables is very poor practice, it's hard to debug and it's error prone. And because the whole approach is wrong anyway because you should approach this as follows:
- put all filenames of the A directory (B and C in your example) in a
std::vector. - for each string in the vector: call
fun1(foldernum ,element);
Code outline:
std::vector<std::string> files;
GetFilesFromDirectory("A", files);
for (auto foldernum = 0; foldernum < files.size(); foldernum++)
{
fun1(foldernum, files[foldernum]);
}
void GetFilesFromDirectory(std::string dirname, std::vector & files)
{
// fill the files vector with filenames of dirname
DIR* dir = opendir(dirname.c_str());
... // 4-5 five more lines you should be able to write on your own
// hint: use files.push_back(entity->d_name) at some point
}
You might need to add some error handling.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
