我写了一些代码来轻松添加目录中的图像文件名,并将它们添加到文本文件中的列表中。这工作正常,但当图像在子文件夹中时,它只会将文件夹名称添加为文本文件中的条目。
我需要它能够检查它是否是一个文件夹,然后将正确的目录添加到文本中,以便可能在子文件夹中的图像,例如subfolder / image.jpg
无法解决我需要添加的内容。这是我到目前为止所得到的......
#include<stdio.h>
#include<cstdlib>
#include<iostream>
#include<string.h>
#include<fstream>
#include<dirent.h>
void listFile();
std::ofstream myfile;
int main(){
listFile();
return 0;
}
void listFile(){
DIR *pDIR;
struct dirent *entry;
if( pDIR=opendir("/home/hduser/Example2Files/TrainImages/") ){
while(entry = readdir(pDIR)){
if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )
myfile.open ("/home/hduser/Example2Files/TrainImages/train.txt",std::ios_base::app);
myfile << entry->d_name << "\n";
myfile.close();
}
closedir(pDIR);
}
}
答案 0 :(得分:1)
要遍历目录,您(可能)必须修改您的代码,以便您拥有一个获取目录名称的函数,并列出该目录中的常规文件。如果找到一个目录,它应该使用当前目录的连接名称和找到的目录递归调用。
要确定文件是否是目录,您可以使用entry.d_type == DT_DIR
之类的内容。