首页 > 编程技术 > C语言查看和更改文件的权限

C语言查看和更改文件的权限

2010年1月25日 转烛 发表评论 阅读评论

  有时候需要在程序里获得某个文件的权限信息,正如在Linux下用ls -l命令可以查看权限,那么在C语言中同样有函数可以实现这样的功能。


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

void main()
{
        char *fileName = "/home/user/test/myfile";
        struct stat fileInfo;

        if (stat(fileName, &fileInfo) < 0)
                exit(0);

        unsigned int mask = 0000777;
        unsigned int access = mask & fileInfo.st_mode;
        printf("%o\n%d\n", access, fileInfo.st_uid);
}

  关于更多的信息,诸如用户和组的信息,fileInfo.st_uid等等,可以查询stat结构,里面有很多的信息。

struct  stat
{
     dev_t    st_dev;       /*device*/
     ino_t     st_ino;        /*inode*/
     mode_t st_mode;    /*protection*/
     nlink_t   st_nlink;     /*number of hard  links */
     uid_t     st_uid;       /*user ID of owner*/
     gid_t     st_gid;       /*group ID of owner*/
     dev_t    st_rdev;     /*device type (if inodedevice)*/
     off_t     st_size;      /*total size,  in bytes*/
     unsigned long  st_blksize;       /*blocksize for filesystem I/O*/
     unsigned long  st_blocks;       /* number of blocks allocated*/
     time_t   st_atime;                 /*time of last access*/
     time_t   st_mtime;                /*time of last modification*/
     time_t   st_ctime;                /*time of last change*/
};

  当然你也可能更改文件的权限信息,譬如本来一个文件是0600的权限,你想更改为0644的权限,即如同Linux下chmod命令。在Linux下我们可以用:

#chmod 0644 myfile

  来更改文件的权限,那么在C语言下,其实也提供了类似的函数。

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

void main()
{
        char *fileName = "/home/user/test/myfile";
        chmod(fileName, 0644);
}

  其实呢,还有更多的函数,跟Linux里的命令很相近。

分类: 编程技术 标签: , , ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.