戏水游鱼的blog

  IT博客 :: 首页 :: 联系 :: 聚合  :: 管理
  2 Posts :: 0 Stories :: 1 Comments :: 0 Trackbacks
      Linux学习笔记的第一部分的最终目的是模拟一个ls命令。下面贴出的是如何获取文件信息的代码

  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <unistd.h>
  5
  6 int main(int argc, char* argv[]) //argc 外部命令的个数 argv 外部命令内容
  7 {
  8     struct stat file_stat;  //定义为stat的结构体file_stat,用于保存文件信息
  9
 10     if(argc != 2){//判断程序是否带有一个参数,没有给出提示。1表示执行程序
 11         printf("Usage:%s filename\n",argv[0]);
 12         return 1;
 13     }
 14
 15     //调用stat函数,如果出错,给出提示
 16     if(stat(argv[1],&file_stat) == -1){
 17         perror("Cannot get the information of the file!\n");
 18         return 1;
 19     }
 20
 21     //使用POSIX中定义的宏判断是否是常规文件
 22     if(S_ISREG(file_stat.st_mode))
 23             printf("%s is regular File,Judged by S_ISREG\n",argv[1]);
 24     //通过st_mode与S_IFREG的位运算判断是否是常规文件(linux提供的方式)
 25     if(file_stat.st_mode & S_IFREG)
 26             printf("%s is regular File,Judged by S_ISREG\n",argv[1]);
 27     //通过S_ISDIR宏判断是否是目录
 28     if(S_ISDIR(file_stat.st_mode))
 29         printf("%s is Directory,Judged by S_ISDIR\n",argv[1]);
 30     //通过st_mode与S_IFDIR的位运算判断是否是目录
 31     if(file_stat.st_mode & S_IFDIR)
 32         printf("%s is Directory,Judged by bit calculate S_ISDIR\n",argv[1]);
 33
 34     //输出file_stat中其他的信息
 35     printf("Owner ID: %d,Group ID: %d\n",file_stat.st_uid,file_stat.st_gid);
 36     printf("Last Access Time: %15s\n",ctime(&file_stat.st_atime));
 37     printf("Last Modification Time: %15s\n",ctime(&file_stat.st_mtime));
 38     printf("Last Status Change Time: %15s\n",ctime(&file_stat.st_ctime));
 39
 40     return 0;
 41 }

执行结果:
              mkdir test;
              ls -l
-rwxr-xr-x 1 zwd zwd 7128 2008-05-06 14:49 open
-rw-r--r-- 1 zwd zwd  672 2008-05-06 14:57 open.c
-rwxr-xr-x 1 zwd zwd 7461 2008-05-10 11:46 stat
-rw-r--r-- 1 zwd zwd 1593 2008-05-10 11:46 stat.c
drwxr-xr-x 2 zwd zwd 4096 2008-05-10 11:46 test
-rw-r--r-- 1 zwd zwd   10 2008-05-06 14:44 test.dat
            ./stat test
test is Directory,Judged by S_ISDIR
test is Directory,Judged by bit calculate S_ISDIR
Owner ID: 1000,Group ID: 1000
Last Access Time: Sat May 10 11:46:21 2008
Last Modification Time: Sat May 10 11:46:21 2008
Last Status Change Time: Sat May 10 11:46:21 2008





stat文件类型可以查看手册Linux programmer's manual
ps:谁能告诉一下,如何将代码呈现高亮,这样看起来比较方便。我在vim上的代码是高亮的,但是不知道如何粘贴。谢谢




posted on 2008-05-10 11:59 戏水游鱼 阅读(587) 评论(1)  编辑 收藏 引用

Feedback

# re: Linux学习笔记(1)--文件信息 2008-05-15 17:07 图书
如何获取文件信息很经典的  回复  更多评论
  

只有注册用户登录后才能发表评论。