Chinaunix

标题: 文件类型判断--fstat [打印本页]

作者: zzxzj2004    时间: 2006-12-24 17:57
标题: 文件类型判断--fstat
这是GNU/LINUX编程指南第十一章中有关fstat的示例,用来判断一个文件是什么类型。
/*************************************
* file_stat.c --Naive file stat program
***************************************/
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char **argv)
{
struct stat buf;
mode_t mode;
char type[80];
int fd;

/* 命令参数 ,判断命令行的参数是不是带文件名*/
if (argc!=2){
  puts("USEAGE: file_stat FileName");
  exit(EXIT_FAILURE);
}

/* 打开文件,打开命令行参数第一个,也就是要判断类型的文件名 */
if ((fd=open(argv[1],O_RDONLY))
//主设备号和次设备号
printf("   MODE:   %#o\n",mode & ~(S_IFMT)); //这个取得访问模式 wrx
printf("   LINKS:  %d\n",buf.st_nlink);//link数
printf("   UID:    %d\n",buf.st_uid);//uid
printf("   GID:    %d\n",buf.st_gid);//gid
if(S_ISLNK(mode))
  strcpy(type,"Symbolic line"); //判断是什么类型,link、普通文件、目录....把值传给type.
else if(S_ISREG(mode))
  strcpy(type,"Regular file");
else if(S_ISDIR(mode))
  strcpy(type,"Directory file");
else if(S_ISCHR(mode))
  strcpy(type,"Character device");
else if(S_ISBLK(mode))
  strcpy(type,"Block device");
else if(S_ISFIFO(mode))
  strcpy(type,"FIFO");
else if(S_ISSOCK(mode))
  strcpy(type,"Socket");
else
  strcpy(type,"Unknown type");
printf("   TYPE:      %s\n",type);
printf("   SIZE:      %ld\n",buf.st_size);
printf("   BLK SIZE:  %ld\n",buf.st_blksize);
printf("   BLOCK:     %d\n",(int)buf.st_blocks);
printf("   accessed:  %s",ctime(&buf.st_atime));
printf("   MODIFIED:  %s",ctime(&buf.st_mtime));
printf("   CHANGED:   %s",ctime(&buf.st_ctime));

/* 关闭文件 */
if(close(fd)

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21905/showart_220468.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2