centos

centos下copendir命令的示例

小樊
41
2025-10-07 03:01:09
栏目: 智能运维

opendir 是一个 C 语言库函数,用于打开一个目录流

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

int main() {
    DIR *dir;
    struct dirent *entry;

    // 打开当前目录
    dir = opendir(".");

    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    // 遍历目录中的所有文件和子目录
    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    // 关闭目录流
    closedir(dir);

    return 0;
}

将此代码保存为 list_directory.c,然后在 CentOS 系统中使用以下命令编译:

gcc list_directory.c -o list_directory

运行编译后的程序:

./list_directory

这将显示当前目录下的所有文件和子目录。如果你想列出其他目录的内容,只需将 opendir 函数中的参数更改为所需目录的路径即可。

0
看了该问题的人还看了