预备知识:
1.stat,fstat,lstat函数返回文件有关的信息结构;
2.lstat函数类似于stat,但是当命名的文件时一个符号链接时,lstat返回该符号链接有关的信息,而不是由该符号链接引用文件的信息;
程序清单:
#include <stdio.h> //for printf
#include <stdlib.h> //for exit
#include <sys/stat.h> //for S_ISREG()/S_ISDIR() and so on
int main(int argc,char *argv[])
{
char *ptr;
struct stat buf;
int i;
for(i=1; i<argc; i++)
{
printf("argv[%d]:%s: ",i,argv[i]);
if(lstat(argv[i],&buf) < 0)
{
perror("lstat error");
continue;
}
if(S_ISREG(buf.st_mode))
ptr = "regular";
else if(S_ISDIR(buf.st_mode))
ptr = "directory";
else if(S_ISCHR(buf.st_mode))
ptr = "character special";
else if(S_ISBLK(buf.st_mode))
ptr = "block special";
else if(S_ISFIFO(buf.st_mode))
ptr = "fifo";
else if(S_ISLNK(buf.st_mode))
ptr = "symbolic link";
else if(S_ISSOCK(buf.st_mode))
ptr = "socket";
else
ptr = "***unknown mode***";
printf("%s\n",ptr);
}
exit(0);
}
|
程序运行结果:
obe-240 test/linuxc> gcc -o stat_test stat_test4.c
obe-240 test/linuxc> ./stat_test /etc /etc/passwd /dev /dev/log /dev/tty \
? /dev/cdrom
argv[1]:/etc: directory
argv[2]:/etc/passwd: regular
argv[3]:/dev: directory
argv[4]:/dev/log: socket
argv[5]:/dev/tty: character special
argv[6]:/dev/cdrom: symbolic link
阅读(1293) | 评论(0) | 转发(0) |