版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/82995507
用第二关的代码修改即可,因为图片属于普通文件,而txt也是普通文件,单纯用stat无法区分,这时我们要提取后缀名进行判断,so easy,见过关代码:
void showDirStructure(char *folderPath)
{
static int flor = 0; //²ãÊý
for (int i = 0; i < flor*2; i++) cout << " "; //Êä³öÇ°Öÿոñ
char buf[256];
int len = 0;
for (int i = strlen(folderPath)-1; folderPath[i] != '/'; i--) buf[len++] = folderPath[i];
buf[len] = '\0';
for (int i = 0; i < len/2; i++) {
char t = buf[i];
buf[i] = buf[len-1-i];
buf[len-1-i] = t;
}
cout << "+--" << buf << endl;
DIR *dir = opendir(folderPath);
struct dirent *i = NULL;
while ((i = readdir(dir)) != NULL) {
if (!strcmp(i->d_name, ".") || !strcmp(i->d_name, "..")) continue;
strcpy(buf, folderPath);
strcat(buf, "/");
strcat(buf, i->d_name);
struct stat M;
stat(buf, &M);
if (S_ISDIR(M.st_mode))
{
flor += 1;
showDirStructure(buf);
flor -= 1;
}
else
{
if (S_ISREG(M.st_mode)) {
char ext[256];
len = 0;
for (int j = strlen(buf)-1; buf[j] != '.'; j--) ext[len++] = buf[j];
ext[len] = '\0';
for (int j = 0; j < len/2; j++) {
char t = ext[j];
ext[j] = ext[len-1-j];
ext[len-1-j] = t;
}
//cout << "test:" << ext << endl;
if (!strcmp(ext, "jpg") || !strcmp(ext, "png") || !strcmp(ext, "bmp")) {
for (int j = 0; j < (flor+1)*2; j++) cout << " ";
cout << "--" << i->d_name << endl;
}
}
}
}
closedir(dir);
}