如何使用C语言读取文件夹中的所有文件

21

我希望能够读取特定文件夹中的所有文本文件。这些文件的名称没有任何共同的模式,否则任务会更容易。

//read a file from the directory  
//Perform a common operation  
//write output to a common file  
//read the next file

如果我可以使用子文件夹一起工作,那就太好了,但是基本实现也足够了。

我试图查看以前提出的相关问题(这里这里这里这里),但它们都没有给出我需要的 C 和 Linux 具体答案。

编辑:所以,根据收到的答案,我写下了以下内容-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>


int main(int argc, char **argv)
{
    DIR* FD;
    struct dirent* in_file;
    FILE    *output_file;
    FILE    *entry_file;
    char    buffer[BUFSIZ];

    /* Opening common file for writing */
    output_file = fopen("/home/pnp/snort_rules_folder/rulesoutput.txt", "a+");
    if (output_file == NULL)
    {
        fprintf(stderr, "Error : Failed to open output_file\n");

        return 1;
    }

    /* Scanning the in directory */
    if (NULL == (FD = opendir ("/home/pnp/snort_rules_folder/rules"))) 
    {
        fprintf(stderr, "Error : Failed to open input directory\n");
        fclose(output_file);

        return 1;
    }
    while ((in_file = readdir(FD))) 
    {
        /* On linux/Unix we don't want current and parent directories
         * If you're on Windows machine remove this two lines
         */
        if (!strcmp (in_file->d_name, "."))
            continue;
        if (!strcmp (in_file->d_name, ".."))    
            continue;
        /* Open directory entry file for common operation */
        /* TODO : change permissions to meet your need! */
        entry_file = fopen(in_file->d_name, "r");
        if (entry_file == NULL)
        {
            fprintf(stderr, "Error : Failed to open entry file\n");
            fclose(output_file);

            return 1;
        }

        /* Doing some stuff with entry_file : */

        while (fgets(buffer, BUFSIZ, entry_file) != NULL)
        {
            /* Use fprintf or fwrite to write some stuff into common_file*/
        }

    fprintf(output_file, "reading file %s", in_file->d_name);

        /* When you finish with the file, close it */
        fclose(entry_file);
    }

    /* Don't forget to close common file before leaving */
    fclose(output_file);

    return 0;
     }

收到的错误信息为-
pnp@pnp-laptop:~/snort_rules_folder$ ./a.out
错误:无法打开条目文件


可能是c:返回目录中的所有文件名的重复问题。 - Greg Hewgill
3
我认为你找不到重复文件的原因在于使用了“文件夹”这个词,而不是更常见的“目录”(至少在Linux平台上是如此)。 - Greg Hewgill
2
你可以使用 find -type f -exec your_program {} + >output.file 命令吗? - jfs
@pnp 我得到了完全相同的错误。你解决了吗? - Ketan Maheshwari
@Ketan 接受的答案(以及评论)对我有用。但这已经太久远了,我记不清太多细节了... - pnp
显示剩余2条评论
1个回答

20
您可以使用此示例代码并根据需要进行修改:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>

/* This is just a sample code, modify it to meet your need */
int main(int argc, char **argv)
{
    DIR* FD;
    struct dirent* in_file;
    FILE    *common_file;
    FILE    *entry_file;
    char    buffer[BUFSIZ];

    /* Openiing common file for writing */
    common_file = fopen(path_to_your_common_file, "w");
    if (common_file == NULL)
    {
        fprintf(stderr, "Error : Failed to open common_file - %s\n", strerror(errno));

        return 1;
    }

    /* Scanning the in directory */
    if (NULL == (FD = opendir (in_dir))) 
    {
        fprintf(stderr, "Error : Failed to open input directory - %s\n", strerror(errno));
        fclose(common_file);

        return 1;
    }
    while ((in_file = readdir(FD))) 
    {
        /* On linux/Unix we don't want current and parent directories
         * On windows machine too, thanks Greg Hewgill
         */
        if (!strcmp (in_file->d_name, "."))
            continue;
        if (!strcmp (in_file->d_name, ".."))    
            continue;
        /* Open directory entry file for common operation */
        /* TODO : change permissions to meet your need! */
        entry_file = fopen(in_file->d_name, "rw");
        if (entry_file == NULL)
        {
            fprintf(stderr, "Error : Failed to open entry file - %s\n", strerror(errno));
            fclose(common_file);

            return 1;
        }

        /* Doing some struf with entry_file : */
        /* For example use fgets */
        while (fgets(buffer, BUFSIZ, entry_file) != NULL)
        {
            /* Use fprintf or fwrite to write some stuff into common_file*/
        }

        /* When you finish with the file, close it */
        fclose(entry_file);
    }

    /* Don't forget to close common file before leaving */
    fclose(common_file);

    return 0;
}

希望这能帮到您。
敬礼。

谢谢。如果您不介意再帮忙一下,这是我修改后的代码- http://pastebin.com/4jFTHY6Z,末尾写有我收到的错误信息。 - pnp
@pnp:您可以编辑您的帖子并在此处发布您的代码,以获得更多帮助。 - TOC
@pnp,pl.请检查您是否从存放文件的同一目录运行代码。如果您从其他目录运行代码,则可能导致fopen无法获取文件的完整路径。此外,您可以添加一个错误报告库函数(例如perror)而不是使用自己的错误处理。这将给出确切的错误信息。现在,如果您要读取的目录包含其他目录(而不是文件),您是否希望对这些目录也应用fopen?似乎不需要。所以,在循环中,如果遇到目录(stat函数可帮助判断),您需要添加一个继续循环的检查。 - Tanmoy Bandyopadhyay
正如@Tanmoy所说,提供您的文件的完整路径,以确保一切正确。此外,添加errno以查看错误信息,我将编辑我的代码以添加该功能。 - TOC
感谢 TOC 添加 errno 报告。同时,我想请求您能否添加代码以获取文件名并判断是否为目录,如果是,则继续循环。这将使答案更好。 - Tanmoy Bandyopadhyay
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接