C程序打印目录中的目录名并排除当前目录和父目录

标签 c linux directory dirent.h

<分区>

我有一个程序,通过检查 d_type == DT_DIR

打印出特定目录中列出的所有目录

程序运行正常,但也打印出父目录 .. 和当前目录 .

我试图设置一个 if 语句来检查 d_name != ".."or ".",但它仍然打印父目录和当前目录

这是我的代码,添加了 if 语句

 directory = opendir("/home/user/adirectory");

    if(directory != NULL)
    {
        while(entry = readdir(directory)) {
            if(entry->d_type == DT_DIR && entry->d_name != ".." && entry->d_name != ".")
                printf("%s\n", entry->d_name);
        }


    }

不幸的是,这是输出,其中 dir2adirectory

中的一个目录
..
dir2
.

我想要一个只显示这个目录而没有一个或两个点的输出

dir2

最佳答案

C 中的字符串比较可以使用strcmp 函数来完成。您不能使用 = 符号比较字符串。以下是使用 strcmp 更新的代码。

directory = opendir("/home/user/adirectory");

    if(directory != NULL)
    {
        while(entry = readdir(directory)) {
            if(entry->d_type == DT_DIR && strcmp(entry->d_name,"..")!=0 && strcmp(entry->d_name, ".")!=0)
                printf("%s\n", entry->d_name);
        }


    } 

关于C程序打印目录中的目录名并排除当前目录和父目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110103/

相关文章:

python - 在 Ubuntu 10.04 中安装 Dropbox python SDK

search - 在 emacs : exclude folders from searching IDs "gid"

c - 如何修复 'Segmentation fault (core dumped)'

c - Linux C套接字-Recvmsg-获取源ifindex

c++ - 在 pthreads 中指定线程堆栈大小

database - 使用 Azure Data Studio 时无法在服务器导航面板中查看数据库列表

python - 替换Python目录中文本文件中的值

c - 在 Linux PCI 驱动程序中向设备添加多个属性

linux - 在 SSHD 配置中, "MaxStartups 10:30:60"是什么意思?

linux - 贝加尔湖需要特定文件夹的写入权限