列出目录中文件的程序

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将使用 dirent.h 头文件创建一个 C 程序,用于列出目录中的所有文件。

注意:你需要自己创建文件 ~/project/main.c,以便练习编码并学习如何使用 gcc 编译和运行它。

cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/FileHandlingGroup(["`File Handling`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/while_loop("`While Loop`") c/CompoundTypesGroup -.-> c/structures("`Structures`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/FileHandlingGroup -.-> c/write_to_files("`Write To Files`") c/FileHandlingGroup -.-> c/create_files("`Create Files`") c/FileHandlingGroup -.-> c/read_files("`Read Files`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123315{{"`列出目录中文件的程序`"}} c/if_else -.-> lab-123315{{"`列出目录中文件的程序`"}} c/while_loop -.-> lab-123315{{"`列出目录中文件的程序`"}} c/structures -.-> lab-123315{{"`列出目录中文件的程序`"}} c/function_declaration -.-> lab-123315{{"`列出目录中文件的程序`"}} c/write_to_files -.-> lab-123315{{"`列出目录中文件的程序`"}} c/create_files -.-> lab-123315{{"`列出目录中文件的程序`"}} c/read_files -.-> lab-123315{{"`列出目录中文件的程序`"}} c/output -.-> lab-123315{{"`列出目录中文件的程序`"}} end

包含头文件

我们需要在程序的开头包含标准输入/输出和 dirent 头文件,代码如下:

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

定义主函数

main() 函数是我们程序的入口点。程序的执行从这里开始。我们还将声明类型为 DIR 的目录指针 d 和类型为 struct dirent 的目录条目指针 dir

int main(void)
{
    DIR *d;
    struct dirent *dir;
    /*Your code goes here*/
    return 0;
}

打开目录

我们将使用 opendir() 函数打开所需的目录。这里的点号(.)表示当前目录。

d = opendir(".");

读取目录

我们将使用 readdir() 函数读取目录中的每个条目。在这里,我们检查目录指针是否为 NULL。如果不是 NULL,我们将打印目录中存在的所有文件。

if (d)
{
    while ((dir = readdir(d)) != NULL)
    {
        printf("%s\n", dir->d_name);
    }
    closedir(d);
}

完整代码

以下是程序的完整代码:

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

int main(void)
{
    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            printf("%s\n", dir->d_name);
        }
        closedir(d);
    }
    return(0);
}

总结

在本实验中,我们学习了如何创建一个 C 程序来列出目录中所有文件的名称。我们使用了 dirent.h 头文件中的函数来实现这一功能。通过使用该程序,我们可以轻松获取指定目录中所有文件的名称。

您可能感兴趣的其他 C 教程