版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32768743/article/details/87471466
刚开始的时候,还在想这个该怎么做,读了源代码,并运行后,开始疑惑怎么传文件描述符,最后在笔记里发现了fstat函数可以解决问题
例子代码
#include "csapp.h"
int main (int argc, char **argv) {
struct stat stat;
char *type, *readok;
Stat(argv[1], &stat);
if (S_ISREG(stat.st_mode)) type = "regular";
else if (S_ISDIR(stat.st_mode)) type = "directory";
else type = "other";
if ((stat.st_mode & S_IRUSR)) readok = "yes";
else readok = "no";
printf("type: %s, read: %s\n", type, readok);
exit(0);
}
运行结果好像不对
加了一个参数,其实例子代码应该加错误处理的,类似
可能只是为了说明,没有写冗余代码吧
按作业要求修改代码
#include "csapp.h"
int main (int argc, char **argv) {
struct stat stat;
char *type, *readok;
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
exit(0);
}
Fstat(atoi(argv[1]), &stat);
if (S_ISREG(stat.st_mode)) type = "regular";
else if (S_ISDIR(stat.st_mode)) type = "directory";
else type = "other";
if ((stat.st_mode & S_IRUSR)) readok = "yes";
else readok = "no";
printf("type: %s, read: %s\n", type, readok);
exit(0);
}
同时做一个简单的错误处理
当传入参数为1时的实验结果
由于命令行传入的数据是char,需要用atoi转换一下,但是atoi没法知道能不能转,如果不是数字,会返回0