C 程序:打印目录中所有文件名称

原文:https://www.studytonight.com/c/programs/files-and-streams/program-to-list-files-in-directory

dirent.h 头文件包含与目录流相关的变量和函数。

下面是一个打印目录中所有文件名称的程序。

#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);
}

File1.txt 文件 2.txt 文件 3.txt 文件 4.txt 文件 5.txt 文件 6.txt 文件 7.txt

我们还可以将目录名作为用户的输入,也可以创建一个简单的 C 程序来搜索目录中的特定文件。