c - 我怎样才能只从c目录中获取txt文件?

标签 c unix char dirent.h

我只想获取给定目录中 *.txt 文件的名称,如下所示:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>

int main(int argc, char **argv)
{
    char *dirFilename = "dir";

    DIR *directory = NULL;

    directory = opendir (dirFilename);
    if(directory == NULL)
        return -1;

    struct dirent *ent;

     while ((ent = readdir (directory)) != NULL)
     {
         if(ent->d_name.extension == "txt")
            printf ("%s\n", ent->d_name);
     }

    if(closedir(directory) < 0)
        return -1;

    return 0;
}

我如何在纯 unix c 中执行此操作?

最佳答案

首先,Unix 没有文件扩展名的概念,所以没有 extension成员(member) struct dirent .其次,您不能将字符串与 == 进行比较。 .你可以使用类似的东西

bool has_txt_extension(char const *name)
{
    size_t len = strlen(name);
    return len > 4 && strcmp(name + len - 4, ".txt") == 0;
}

> 4部分确保文件名 .txt不匹配。

(从 bool 获得 <stdbool.h> 。)

关于c - 我怎样才能只从c目录中获取txt文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12976733/

相关文章:

C语法问题

php - 如何从另一个 php 扩展方法调用 php 扩展方法

java - 将 C 中的十六进制数组转换为 C 中的 long 到 Java 中的 String

unix - ksh 将字符串拆分为数组以写入文件

c# - 将 char[,] 数组转换为 char**

c - windows xp下如何监控windows服务的状态变化?

python - pathlib.Path.chmod(mode) 中模式的解释

linux - 在 Linux 上使用 AF_LOCAL 或 AF_UNIX 套接字进行多播?

ios - nsdata dataWithBytes 在 iOS7 上导致崩溃

c - 为 2 个指针分配相同的值,而不是使它们的引用相等(C 中的指针)