以下代码使用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 = %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; }
示例运行如下所示:
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
原文地址:https://www.jb51.cc/bash/387247.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。