gpt4 book ai didi

c - 读取文件夹中的所有 .txt 文件?

转载 作者:行者123 更新时间:2023-11-30 16:37:22 25 4
gpt4 key购买 nike

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

最佳答案

这不是答案,但对于评论来说太大了

这是您的问题:

1.

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

这对于一个文件来说已经足够了。这还不够

  • 之后

    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 结尾

  • 考虑使用fstat来确保文件是文本文件

  • 删除 malloc 上的强制转换

  • 也许对文件使用realloc

  • while ... feof 不好 - 请参阅上面的链接

  • fscanf(file, "%s", - 缓冲区可能会溢出。对此采取措施。阅读手册页

  • 关于c - 读取文件夹中的所有 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970524/

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