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

问题描述 投票:0回答:1

我正在尝试读取名为“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-> d_name);”是“。”。我哪里做错了?

c
1个回答
0
投票

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

这是你的问题:

1.

 files = (FILES *)malloc(sizeof(FILES));

这足够大一个FILES。这还不够

  1. while((filesInDirectory = readdir(directory)) != NULL){

放点像

size_t len = strlen(filesInDirectory->d_name);
if (len < 5 || strcmp(filesInDirectory->d_name + len - 4, ".txt") != 0) {
  continue;
}

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

  1. 考虑使用fstat来确保文件是文本文件
  2. 删除malloc上的强制转换
  3. 也许使用reallocfiles
  4. while ... feof很糟糕 - 请参阅上面的链接
  5. fscanf(file, "%s", - 缓冲区溢出是可能的。做点什么吧。阅读手册页
© www.soinside.com 2019 - 2024. All rights reserved.