文件和目录一

2019-07-20  本文已影响0人  suntwo

stat函数

int stat(const char *restrict *pathname,struct stat * restrict buf)
int fstat(int fd,struct stat *buf)
int lstat(const char *restrict *pathname,struct stat * restrict buf)

这几个函数用来获取文件后者目录的基本信息,第一个函数有两个参数,第一个表示文件或目录的名字,第二个为stat类型的指针。第二个函数第一个参数为文件描述符,第二个参数为stat类型的指针。第三个函数的参数和第一个一样,但是和第一个函数的功能不同,当文件或目录是一个链接文件时第一个函数得到信息是被链接的文件,第三个是这个链接的文件的信息。

stat类型的介绍

struct stat{
mode_t st_mode;
ino_t st_ino;
uid_t st_uid;
gid_t st_gid;
off_t st_size;
.
.
.

}

可以看到这个结构包含很多文件的信息,有文件的用户id和组id,st_mode为文件的权限位和文件类型等信息,st_size表示文件的大小。
下面是几个操作st_mode的几个函数

S_ISREG()
S_ISDIR()
S_ISCHR()
S_ISBLK()
S_ISLNK()
S_ISFIFO()
S_ISSOCK()

这几个函数用来判断文件的类型,使用if(S_ISDIR(buf.st_mode))这样的格式来判断文件的类型。
下面是一个例子

#include"head.h"
int main(int argc,char *argv[])
{
if(argc<2)
{
printf("param number error\n");
return 0;
}
int i;
char *p;
struct stat buf;
for(i=1;i<argc;++i)
{
stat(argv[i],&buf);
if(S_ISREG(buf.st_mode))
p="regular";
else if(S_ISDIR(buf.st_mode))
p="directory";
else if(S_ISCHR(buf.st_mode))
p="charecter special";
else if(S_ISBLK(buf.st_mode))
p="block special";
else if(S_ISLNK(buf.st_mode))
p="link file";
else
p="unkown type";
printf("%s\n",p);
}
return 0;
}

测试:
root@ubuntu:/home/sun/project/dirent# ./stat2 stat1 stat2 / /usr
regular
regular
directory
directory

文件创建屏蔽字

mode_t umask(mode_t cmask)

这个函数的作用是更改文件创建屏蔽字,当我们创建一个文件时,创建文件权限的结果可能和我们编写的不一样,这是因为文件创建屏蔽字的存在,文件创建屏蔽字的作用便是将某个权限设置的不起作用。
下面我们使用一个例子来进行说明。

root@ubuntu:/home/sun/project/dirent# umask
0022
#include"head.h"
#define RWXALL (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH)
int main()
{
creat("bb1.txt",RWXALL);
mode_t old=umask(0);
creat("bb2.txt",RWXALL);
umask(old);
return 0;
}
结果:
-rwxr-xr-x 1 root root    0 7月  19 17:56 bb1.txt
-rwxrwxrwx 1 root root    0 7月  19 17:56 bb2.txt

更改文件的访问权限

int chmod(const char *pathname,mode_t mode)
int fchmod(int fd,mode_t mode)
成功返回0,失败返回-1

这两个函数的第一个参数表示文件名和文件打开的描述符。
下面是第二个参数mode

S_ISUID  执行时设置用户id
S_ISGID  执行时设置组id
S_IRWXU  用户读写执行
S_IRUSR
S_IWUSR
S_IXUSR
S_IRWXG  组读写执行
S_IRGRP
S_IWGRP
S_IXGRP
S_IRWXO  其他读写执行
S_IROTH
S_IWOTH
S_IXOTH
上一篇 下一篇

猜你喜欢

热点阅读