从文件夹中读取所有.txt文件?

时间:2017-12-25 16:57:58

标签: c

我正在尝试读取名为“dataset”的目录中的所有.txt文件。所有文本文件的名称都是1.txt,2.txt,3.txt ......然后将文件内容保存到名为FILES的结构中。

我在一些来源中使用了dirent.h库和readdir()函数。但是从目录中读取的程序的文件名不能正确返回。这是我的相关代码:

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

typedef struct FILES{
    char **words;
    int wordCount;
}FILES;

void readFiles();

FILES *files;
int fileCount;

int main(){
    readFiles();

    return 0;
}

void readFiles(){
    FILE *file;
    DIR *directory;
    struct dirent *filesInDirectory;
    int counter;

    fileCount = 1;
    files = (FILES *)malloc(sizeof(FILES));
    directory = opendir("dataset");
    if(directory == NULL){
        printf("Warning: The directory name that is given in the code is not 
valid ..!");
        return;
    }else{
        while((filesInDirectory = readdir(directory)) != NULL){
            printf("%s\n", filesInDirectory->d_name);
            file = fopen(filesInDirectory->d_name, "r+");
            if(file == NULL){
                printf("Warning: The file named %s could not open ..!", 
filesInDirectory->d_name);
                return;
            }
            files[fileCount-1].wordCount = 1;
            files[fileCount-1].words = (char **)malloc(files[fileCount-
1].wordCount * sizeof(char *));
            counter = 0;

            while(!feof(file)){
                files[fileCount-1].words[counter] = (char *)malloc(20 * 
sizeof(char));
                fscanf(file, "%s", files[fileCount-1].words[counter]);
                files[fileCount-1].wordCount++;
                files[fileCount-1].words = (char **)realloc(files[fileCount-
1].words, files[fileCount-1].wordCount * sizeof(char *));
                counter++;
            }
            fileCount++;            
            fclose(file);
        }
    }

}

我在这里打印的文件名“printf(”%s \ n“,filesInDirectory-&gt; d_name);”是“。”。我在哪里做错了?

1 个答案:

答案 0 :(得分:0)

这不是一个回答但是很难评论

以下是您的问题:

1

FILES

这个尺寸足够while((filesInDirectory = readdir(directory)) != NULL){ 。这还不够

  1. 之后
    size_t len = strlen(filesInDirectory->d_name);
    if (len < 5 || strcmp(filesInDirectory->d_name + len - 4, ".txt") != 0) {
      continue;
    }
    
  2. 添加类似

    的内容
    fstat

    这将检查以确保文件以.txt结尾

    1. 考虑使用realloc确保文件是文本文件

    2. 删除malloc

    3. 上的演员表
    4. 或许files

    5. 使用while ... feof
    6. fscanf(file, "%s",不好 - 请参阅上面的链接

    7. {{1}} - 缓冲区溢出是可能的。做点什么吧。阅读手册页

相关问题