检查文件是否在C特定类型 [英] Check if a file is a specific type in C

查看:184
本文介绍了检查文件是否在C特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写我的第一个C程序,虽然我来自一个C ++的背景。

I'm writing my first C program, though I come from a C++ background.

我需要通过文件的目录遍历和检查,看看是否该文件是一个头文件,然后返回计数。

I need to iterate through a directory of files and check to see if the file is a header file, and then return the count.

我的code如下,它是pretty简陋,我认为:

My code is as follows, it's pretty rudimentary I think:

static int CountHeaders( const char* dirname ) {

    int header_count = 0;
    DIR* dir_ptr;
    struct dirent* entry;

    dir_ptr = opendir( dirname );

    while( ( entry = readdir( dir_ptr ) ) )
    {
        if ( entry->d_type == DT_REG )
        {
            //second if statement to verify the file is a header file should be???
            ++header_count;
        }
    }

    closedir( dir_ptr );

    return header_count;
}

这将是一个很好的if语句来检查,看看是否该文件是一个头?

What would be a good if statement to check to see if the file is a header?

推荐答案

简单检查,如果文件扩展名是 .H ,是这样的:

Simply check if the file extension is .h, something like:

const char *ext = strrchr (entry->d_name, '.');     
if ((ext != NULL) && (!strcmp (ext+1, "h"))) {
     // header file
}

Ofcourse,请注意,这是假定所有的头文件,有一个 .H 扩展,这可能会或可能不会是真实的,C标准并不要求头文件必须有一个 .H 扩展。

Ofcourse, note that this assumes all your header files have an .h extension, which may or may not be true, the C standard does not mandate that header files must have an .h extension.

这篇关于检查文件是否在C特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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