首页 文章

Open()系统调用目录和访问子目录中的文件

提问于
浏览
0

我正在尝试打开一个目录并访问它的所有文件和子目录以及子目录文件等(递归) . 我知道我可以通过使用opendir调用来访问文件和子目录,但我想知道是否有办法通过使用open()系统调用(以及如何?),或者是否打开系统调用只是指文件?

#include <stdio.h> 
#include <dirent.h> 

int main(void) 
{ 
 struct dirent *de;  // Pointer for directory entry 

// opendir() returns a pointer of DIR type.  
DIR *dr = opendir("."); 

if (dr == NULL)  // opendir returns NULL if couldn't open directory 
{ 
    printf("Could not open current directory" ); 
    return 0; 
} 


while ((de = readdir(dr)) != NULL) 
        printf("%s\n", de->d_name); 

closedir(dr);     
return 0; 
 }

下面的代码给出了我目录中文件的名称和子文件夹的名称,但是如何将文件与子文件夹区别开来,以便我可以使用递归来访问子文件夹中的文件?

任何帮助,将不胜感激

1 回答

  • 0

    如果你想检查它是否是一个文件,你可以使用相同的方法但是使用宏S_ISREG,你需要有struct stat和宏S_ISDIR . 此外,当您使用结构时,最好在使用它们之前分配内存 .

    #include <stdio.h> 
    #include <dirent.h> 
    #include <sys/stat.h>
    
    int main(void) 
    { 
     struct dirent *de = malloc(sizeof(struct dirent));  // Pointer for directory entry 
     struct stat *info; = malloc(sizeof(struct stat));
    
    // opendir() returns a pointer of DIR type.  
    DIR *dr = opendir("."); 
    
    if (dr == NULL)  // opendir returns NULL if couldn't open directory 
    { 
        printf("Could not open current directory" ); 
        return 0; 
    } 
    
    
    while ((de = readdir(dr)) != NULL) 
     {
       if((S_ISDIR(info->st_mode)
        printf("Directory:%s \n", de->d_name); 
       else printf("File:"%s \n,de->d_name);
     }
    closedir(dr);     
    return 0; 
    }
    

相关问题