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

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

问题描述

给定一个路径,比如说,/ home / SHREE /路径/闪避,我想,以确定是否高清是一个目录或文件。是否有C或C ++ code实现这一目标的一种方式?

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?

推荐答案

以下code使用 STAT()函数和 S_ISDIR ('是一个目录')和 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>\n");
        printf ("       where <fileSpec> is the file to check.\n");
        return 1;
    }

    // Get the status of the file system object.

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

    // Tell us what it is then exit.

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

    return 0;
}

样品运行如下所示:

Sample runs are shown here:


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天全站免登陆