我編寫了一小段代碼來輕鬆添加目錄中圖像的文件名,並將它們添加到文本文件的列表中。這工作得很好,但是當圖像位於子文件夾內時,它只會將文件夾名稱添加到文本文件中。將文件夾中的圖像文件名寫入文本文件C++
我需要它能夠檢查它是否是一個文件夾,然後添加正確的目錄到文本的圖像,這可能是在子文件夾內,例如子文件夾/ 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);
}
}
你需要使'listFile'成爲一個遞歸函數。讓它只需要一個參數即被讀取的目錄名稱。然後你可以在你遇到的任何目錄中調用它。 – paddy