0

此功能应显示目录中的文件列表,但它仅适用于其他目录中的 C:\Users\"name"\Desktop 以所有名称显示(目录)我尝试过其他方式但只有这有效(不知何故)

# include <stdlib.h>
# include <dirent.h>
# include <sys/types.h>
# include <stdio.h> 
   int list(){
        char s[50];
        struct dirent *entry;
        printf("Specify directory for list of files\n");
        scanf("%s", &s);
        DIR *dir = opendir(s);
        FILE* ff;
        if (dir){
                printf("\n\n******\n\n");
                while ((entry = readdir(dir)) != NULL) {
                ff = (fopen(entry->d_name, "r"));

                if (ff != NULL){
                    printf("%s\n",entry->d_name);
                    fclose(ff); 
                }
                else if (ff == NULL) {
                printf("%s(directory)\n",entry->d_name);
                }

            }
            printf("\n******\n");
            closedir(dir);
            return 1;
        }
4

1 回答 1

2

如果您检查其中的内容,entry->d_name您会发现它只包含文件名而不是完整路径。因此,当您尝试打开文件时,除非该文件存在于当前目录中,否则它无法打开。您需要构建完整路径并使用它来打开文件。

char fullname[1024];
strcpy(fullname,s);
strcat(fullname,"\\");
strcat(fullname,entry->d_name);
ff = fopen(fullname, "r");
于 2018-12-17T11:06:03.693 回答