linux C语言如何得到一个文件的权限并输出

linux C语言如何得到一个文件的权限并输出,第1张

/*-楼主可以参考一下我写的这段程序---------*/

/*-----用stat函数得到文件信息,并用函数转化为文本输出,就跟ls命令一样-----*/

/*----------注释我写得很详细,望采纳-----------*/

#include <sys/types.h>/*-----这三个头文件一定要有-*/

#include <sys/stat.h>

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void mode_to_letter(int mode,char *str)

{

/*-------这个函数用来把模式值转化为字符串------*/

str[0]='-'/*------这里的S_*****都是宏定义,用来判断模式属性-*/

if(S_ISDIR(mode)) str[0]='d'/*-文件夹-*/

if(S_ISCHR(mode)) str[0]='c'/*-字符设备-*/

if(S_ISBLK(mode)) str[0]='b'/*-块设备-*/

if(mode &S_IRUSR) str[1]='r'/*--用户的三个属性-*/

else str[1]='-'

if(mode &S_IWUSR) str[2]='w'

else str[2]='-'

if(mode &S_IXUSR) str[3]='x'

else str[3]='-'

if(mode &S_IRGRP) str[4]='r'/*--组的三个属性-*/

else str[4]='-'

if(mode &S_IWGRP) str[5]='w'

else str[5]='-'

if(mode &S_IXGRP) str[6]='x'

else str[6]='-'

if(mode &S_IROTH) str[7]='r'/*-其他人的三个属性-*/

else str[7]='-'

if(mode &S_IWOTH) str[8]='w'

else str[8]='-'

if(mode &S_IXOTH) str[9]='x'

else str[9]='-'

str[10]='\0'

}

int main(int argc,char *argv[])

{

struct stat sb/*- 定义stat结构--*/

char str[12]

if(argc!=2){

fprintf(stderr,"Usage: %s <pathname>\n",argv[0])

exit(EXIT_FAILURE)

}

if(stat(argv[1],&sb)==-1){/*-stat函数,详情请 man 2 stat 查看 -*/

perror("stat")

exit(EXIT_FAILURE)

}

printf("Mode:%lo(octal)\n",(unsigned long)sb.st_mode)

mode_to_letter(sb.st_mode,str)

printf("Mode:%s\n",str)

return 0

}

1、调整文件的权限命令:chmod

Linux的每个文件都定义了文件的拥有者:u(user)、拥有组:g(group)、其他人:o(others)权限,对应的权限用rwx的组合来定义。使用chmod命令,增加权限用+,删除权限用-,某个文件详细的权限用=号。

比如:

chmod u+r filename  #给某文件增加读的权限

chmod u-r filename  #给某文件删除读的权限

chmod u+w filename  #给某文件增加写的权限

chmod u-w filename  #给某文件删除写的权限

chmod u+x filename  #给某文件增可执行的权限

chmod u-x filename  #给某文件删除可执行的权限

chmod u+rwx filename  #给某文件增加读写可执行的权限

chmod u=rwx filename  #给某文件设定读写可执行的权限

通过这种方式可以同一时刻给文件拥有者、文件拥有组、或其他用户设置权限,如果想要同时设置所有用户的权限就要使用数字表示的方式了,Linux规定 r=4,w=2,x=1。比如权限rwx:7,r-x:5。如果想设置一个文件拥有者有读、写、执行,拥有组的权限是读、执行、其他人只读的话,可以使用命令:chmod 745 filename 进行设置。chmod -R 745 dirname #用来看设置目录权限 必须加 -R参数。

2、改变文件的拥有者命令:chown

比如:chown user1 hello.txt 

#将hello.txt 文件拥有者修改为 user1, 前提user1 为系统中拥有的用户

chown :user1 hello.txt 

#将hello.txt 文件拥有者修改为 user1组, 前提user1 为系统中拥有的用户组

chown user1:user1 hello.txt 

#相当于执行了上面两条命令

chown user1:user1 dirname 

#修改目录的文件拥有者和用户组 需要加 -R参数

3、修改文件的拥有组命令:chgrp

比如:

chgrp user1 hello.txt 

#将hello.txt 文件用户组修改为 user1

chgrp user1 dirname 

#将dirname 目录用户组修改为 user1,需要加 -R参数

觉得不错请点赞支持,欢迎留言或进我的个人群855801563领取【架构资料专题目合集90期】、【BATJTMD大厂JAVA面试真题1000+】,本群专用于学习交流技术、分享面试机会,拒绝广告,我也会在群内不定期答题、探讨。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/8659675.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-19
下一篇2023-04-19

发表评论

登录后才能评论

评论列表(0条)

    保存