区分unix目录和C和C中的文件
发布时间:2020-12-15 19:04:47 所属栏目:安全 来源:网络整理
导读:给定一个路径,比如/ home / shree / path / def,我想确定def是目录还是文件.有没有办法在C或C代码中实现这一点? 以下代码使用stat()函数和S_ISDIR(‘是目录’)和S_ISREG(‘是常规文件’)宏来获取有关该文件的信息.其余的只是错误检查,足以制作完整的可编译
给定一个路径,比如/ home / shree / path / def,我想确定def是目录还是文件.有没有办法在C或C代码中实现这一点?
以下代码使用stat()函数和S_ISDIR(‘是目录’)和S_ISREG(‘是常规文件’)宏来获取有关该文件的信息.其余的只是错误检查,足以制作完整的可编译程序.
#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 = %dn",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; } 示例运行如下所示: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- scala – 使用oozie工作流启动spark程序
- WebServices入门
- angularjs – 在ng-repeat内部按钮以更新表单中的输入
- Bootstrap的js插件之轮播(carousel)
- Docker命令
- Scala:使用StateT monad转换器组成的选项的错误推断类型
- twitter-bootstrap – Twitter Bootstrap:没有匹配的Typea
- Redis系列(三):redisServer、redisDb、redisObject、sds
- angularjs – 如何不发送带有请求体的url模板参数?
- ServiceMix做内部服务器发布WebService(附带案例源码)