在C和C UNIX目录和文件区分++

编程入门 行业动态 更新时间:2024-10-28 08:17:09
本文介绍了在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目录和文件区分++

本文发布于:2023-10-08 23:52:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474117.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   目录   UNIX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!