linux文件操作(stat,chmod,umask)

首次尝试将程序“变种”,用一段程序包含以下几个知识点。详见注释吧。【代码】file.c#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <fcntl.h>int main(int argc,char* argv[]){struct stat file_stat;int fd;if(2 != argc)//1{printf(“Usage: %s filename\n”,argv[0]);return 1;}if(stat(argv[1],&file_stat) == -1)//2{perror(“Can’t get the information of the file!”);return 1;}if(S_ISREG(file_stat.st_mode)) //3{printf(“This is a regular file judged by S_ISREG.\n”);}if(file_stat.st_mode & S_IFREG){printf(“This is a regular file judged by S_IFREG.\n”);}printf(“Owner ID: %d, Group ID: %d.\n”,file_stat.st_uid,file_stat.st_gid);printf(“Permission[before modified]: %o\n.”,file_stat.st_mode & 0x1ff); //4if(chmod(argv[1],S_IRUSR|S_IWUSR|S_IXUSR|S_IWGRP|S_IWOTH)<0) //5{perror(“Can’t modify the permission of the file.\n”);return 1;}else{if(stat(argv[1],&file_stat) == -1){perror(“Can’t get the information of the file!”);return 1;}else{printf(“Permission[after modified]: %o\n.”,file_stat.st_mode & 0x1ff);}}umask(S_IWGRP | S_IRGRP | S_IXGRP | S_IROTH | S_IWOTH |S_IXOTH); //6fd = open(“test2”,O_CREAT | O_RDWR, 0777);if(fd<0){perror(“Fail to creat file.\n”);return 1;}close(fd);if(stat(“test2”,&file_stat) == -1){perror(“Fail to get the information of file test2.\n”);return 1;}printf(“After modify umask value, permission is %o.\n”,file_stat.st_mode & 0x1ff);return 0;}【说明】(1)argc=2,表示指针数组argv[]内部参数个数为2个,第一个指针指向字符串为可执行文件名,第二个指针指向执行时命令行的第一个参数。本程序执行只需要带一个参数,即一个已创建的文件名称。(2)stat函数是通过指向路径的指针获得相关文件信息,该指针即为argv[]第二个参数指针,并将该文件信息写入stat函数第二个参数结构体内部。(3)宏S_ISREG和S_IFERG都是用来检查文件类型,是否为常规文件,实现等价。此外还有检查文件是否为字符设备、块设备、符号链接等。(4)file_stat.st_mode & 0x1ff:0x1ff换算为8进制为777,通过按位与运算计算权限。linux下文件的权限表示可以用三个8进制数表示,分别为u(用户主)-g(同组用户)-o(其他用户),每个8进制数的三个位分别表示读-写-执行权限,1表示有,0表示没有;另外ls命令显示的也是权限的一种,比如rw-r–r–表示用户主具有读写权限,同组和其他用户具有读权限。也就是说rw-r–r–和644等价。(5)创建的文件默认权限就是644,通过chmod可以修改权限,S_IRUSR|S_IWUSR|S_IXUSR|S_IWGRP|S_IWOTH表示用户组权限读写执行,group和other为写权限,这样权限值就变为722了。(6)出于安全考虑,linux新创建的文件,所有类型用户都是没有写权限的。默认的掩码是022,也就是说新创建文件的默认权限是666-022=644,即ls显示的rw-r–r–。umask(S_IWGRP | S_IRGRP | S_IXGRP | S_IROTH | S_IWOTH |S_IXOTH)以后umask=077,因此用777创建,以后的权限实际值为777-077=700.【执行结果】gaolu@gaolu-desktop:~$gaolu@gaolu-desktop:~$ gcc -o file file.cgaolu@gaolu-desktop:~$ ./file testfileThis is a regular file judged by S_ISREG.This is a regular file judged by S_IFREG.Owner ID: 1000, Group ID: 1000.Permission[before modified]: 644Permission[after modified]: 722After modify umask value, permission is 700.gaolu@gaolu-desktop:~$gaolu@gaolu-desktop:~$

淡泊明志,宁静致远

穿越茫茫人海,寻找属于我们的那一份宁静。

linux文件操作(stat,chmod,umask)

相关文章:

你感兴趣的文章:

标签云: