如何从c目录只有txt文件? [英] How can I get only txt files from directory in c?

查看:193
本文介绍了如何从c目录只有txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to get names of only *.txt files in given directory, sth like this:

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

如何在纯unixs中执行此操作?

How can I do this in pure unixs c?

推荐答案

首先,Unix没有文件扩展名的概念,因此 c $ c> struct dirent 。第二,你不能比较字符串与 == 。您可以使用

Firstly, Unix has no notion of file extensions, so there's no extension member on struct dirent. Second, you can't compare strings with ==. You can use something like

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

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

The > 4 part ensures that the filename .txt is not matched.

code> bool 来自< stdbool.h> 。)

(Obtain bool from <stdbool.h>.)

这篇关于如何从c目录只有txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆