区分 C 和 C++ 中的 unix 目录和文件 [英] Differentiate between a unix directory and file in C and C++

查看:27
本文介绍了区分 C 和 C++ 中的 unix 目录和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个路径,比如/home/shree/path/def,我想确定 def 是一个目录还是一个文件.有没有办法在 C 或 C++ 代码中实现这一点?

Given a path, say, /home/shree/path/def, I would want to determine if def is a directory or a file. Is there a way of achieving this in C or C++ code?

推荐答案

以下代码使用了 stat() 函数和 S_ISDIR ('is a directory')和 S_ISREG('是一个普通文件')宏来获取文件的信息.剩下的只是错误检查,足以制作一个完整的可编译程序.

The following code uses the stat() function and the S_ISDIR ('is a directory') and S_ISREG ('is a regular file') macros to get information on the file. The rest is just error checking and enough to make a complete compilable program.

#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>

int main (int argc, char *argv[]) {
    int status;
    struct stat st_buf;

    // Ensure argument passed.

    if (argc != 2) {
        printf ("Usage: progName <fileSpec>
");
        printf ("       where <fileSpec> is the file to check.
");
        return 1;
    }

    // Get the status of the file system object.

    status = stat (argv[1], &st_buf);
    if (status != 0) {
        printf ("Error, errno = %d
", errno);
        return 1;
    }

    // Tell us what it is then exit.

    if (S_ISREG (st_buf.st_mode)) {
        printf ("%s is a regular file.
", argv[1]);
    }
    if (S_ISDIR (st_buf.st_mode)) {
        printf ("%s is a directory.
", argv[1]);
    }

    return 0;
}

示例运行如下所示:


pax> vi progName.c ; gcc -o progName progName.c ; ./progName
Usage: progName 
       where  is the file to check.

pax> ./progName /home
/home is a directory.

pax> ./progName .profile
.profile is a regular file.

pax> ./progName /no_such_file
Error, errno = 2

这篇关于区分 C 和 C++ 中的 unix 目录和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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