手机版
你好,游客 登录 注册
背景:
阅读新闻

Linux 程序设计学习笔记----Linux下文件类型和属性管理

[日期:2014-08-02] 来源:Linux社区  作者:suool [字体:大 中 小]

文件的属性管理

1.读取文件属性

使用stat函数,如下示例:

Linux 程序设计学习笔记----Linux下文件类型和属性管理

stat的结构体包含的如下:主要见stat.h头文件,具体该文件的解读参见:http://www.linuxidc.com/Linux/2011-08/40701.htm  与 http://www.linuxidc.com/Linux/2011-02/32277.htm 

The structurestatcontains at least the following members:

struct stat {
    dev_t        st_dev;      //文件的设备编号
    ino_t        st_ino;      //节点
    mode_t        st_mode;      //文件的类型和存取的权限
    nlink_t      st_nlink;    //连到该文件的硬连接数目,刚建立的文件值为1
    uid_t        st_uid;      //用户ID
    gid_t        st_gid;      //组ID
    dev_t        st_rdev;      //(设备类型)若此文件为设备文件,则为其设备编号
    off_t        st_size;      //文件字节数(文件大小)
    unsigned long st_blksize;  //块大小(文件系统的I/O 缓冲区大小)
    unsigned long st_blocks;    //块数
    time_t        st_atime;    //最后一次访问时间
    time_t        st_mtime;    //最后一次修改时间
    time_t        st_ctime;    //最后一次改变时间(指属性)
};

同样具有查询功能的函数有lstat,参见http://pubs.opengroup.org/onlinepubs/7908799/xsh/lstat.html

正在打开文件的查询函数:fstat,参见http://pubs.opengroup.org/onlinepubs/7908799/xsh/fstat.html

同样上文中的修改命令中,对于已经打开的文件,使用fchmod的类型,加f前缀。

下面是一个使用lstat函数查询文件属性的示例程序,可以根据文件的类型打印对应的提示信息。

代码如下:

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
 int i;
 struct stat buf;
 char *ptr;
 for (i = 1; i < argc; i++)
 {
  printf("%s: ", argv[i]);
  if (lstat(argv[i], &buf) < 0)  // obtains information about the file
  {
   perror("lstat");
   continue;
  }
  if(S_ISREG(buf.st_mode))
   ptr = "regular file";                        // regular file
  else if (S_ISDIR(buf.st_mode)) 
   ptr = "directory file";                      // directory file
  else if (S_ISCHR(buf.st_mode)) 
   ptr = "character special file";              // character_special file
  else if (S_ISBLK(buf.st_mode)) 
   ptr = "block special file";                  // block_special file
  else if (S_ISFIFO(buf.st_mode))
   ptr = "fifo file";                          // pip file

#ifdef S_ISLNK
  else if (S_ISLNK(buf.st_mode)) 
   ptr = "symbolic link";                      // link file
#endif
#ifdef S_ISSOCK
  else if (S_ISSOCK(buf.st_mode)) 
   ptr = "socket";                              // socket file
#endif
  else 
   ptr = "** unknown mode **";                // unknown file

  printf("%s\n", ptr);
 }
 return 0;
}

Linux 程序设计学习笔记----Linux下文件类型和属性管理

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-08/104984.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款