gpt4 book ai didi

C:读取一个目录下的所有*.txt文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:13 30 4
gpt4 key购买 nike

我正在尝试编写一个程序来读取目录中的所有 .txt 文件。它使用 file->d_name 获取每个文件的名称,但现在我需要打开文件才能使用它们。

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

int main (int argc, char *argv[]) {

DIR *directory;
struct dirent* file;
FILE *a;
char ch;

if (argc != 2) {
printf("Error\n", argv[0]);
exit(1);
}

directory = opendir(argv[1]);
if (directory == NULL) {
printf("Error\n");
exit(2);
}

while ((file=readdir(directory)) != NULL) {
printf("%s\n", file->d_name);

// And now????

}

closedir(directory);
}

最佳答案

你写道:

while ((file=readdir(directory)) != NULL) {
printf("%s\n",file->d_name);
//And now????
}
  1. 检查目录条目是文件还是目录。如果它不是常规文件,则移至下一个目录条目。

    if ( file->d_type != DT_REG )
    {
    continue;
    }
  2. 我们有文件。通过组合目录名和目录条目中的文件名来创建文件名。

    char filename[1000]; // Make sure this is large enough.
    sprintf(filename, "%s/%s", argv[1], file->d_name);
  3. 使用标准库函数打开并读取文件内容。

    FILE* fin = fopen(filename, "r");
    if ( fin != NULL )
    {
    // Read the contents of the file
    }
  4. 在处理下一个目录条目之前关闭文件。

    fclose(fin);

关于C:读取一个目录下的所有*.txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33579223/

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