gpt4 book ai didi

C 编程在目录中打开目录

转载 作者:行者123 更新时间:2023-11-30 19:07:20 25 4
gpt4 key购买 nike

#include <dirent.h> 
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int program(char* file) {
DIR *d;
struct dirent *dir;
d = opendir(file);
if (d) {
while ((dir = readdir(d)) != NULL) {
if(dir->d_type == DT_DIR) {
if(opendir(dir->d_name)!=NULL) {
printf("Open successful! ");
}
printf("Is a dir! ");
}

printf("%s\n", dir->d_name);
}

closedir(d);
}

return(0);

}

假设我像这样访问 C 程序中的一个目录,并且发现它的其中一个条目也是一个目录?我如何打开这个目录条目?我认为我的代码没有正确执行

最佳答案

此代码递归调用函数来列出文件和目录。

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int main(void) {
listdir(".", 0); //Call the function for the current path
}

/* Function to list files and directories
* @parameter Name : Name is the path
* @parameter indent: indentation for printing the files and directories
in the hierarchical structure
*/
void listdir(const char *name, int indent)
{
DIR *dir;
struct dirent *entry;

/* Base Case, return if the current file is not directory */
if (!(dir = opendir(name)))
return;

/*Loop for all the files in the current directory */
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char path[1024];

/* If the path is . (current path) or .. (parent of the current
directory) then continue (do not call lisdir()),
we don't want to stuck in infinite situation!
*/
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
printf("%*s[%s]\n", indent, "", entry->d_name);

/* Call the function again for the current path
Add 2 to indentation, that is to leave 2 more spaces in the
hierarchical structure
*/
listdir(path, indent + 2);
} else {
printf("%*s- %s\n", indent, "", entry->d_name);
}
}
closedir(dir);
}

关于C 编程在目录中打开目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com