linux c chmod 更改权限函数

chmod函数:
1.原型:

#include<sys/types.h>
#include<sys/stat.h>
 
int chmod(const char *pathname, mode_t mode);

2.功能:
  依参数mode权限来更改参数pathname指定文件的权限。
3.示例:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>	//基本系统数据类型
#include <sys/stat.h>	//文件状态

//argc记录了用户在运行程序的命令行中输入的参数的个数
//**argv:或者认为是*argv[]字符串指针数组,每一个元素指向一个在命令行输入的参数
//编译器将输入参数的信息放入main函数的参数列表中
//赋值过程是编译器完成的,我们只需要读出数据就可以了
int main(int argc, char **argv)
{
    int mode;     //权限
    int mode_u;   //所有者user的权限
    int mode_g;   //所属组group的权限
    int mode_o;   //其他用户other的权限
    char *path;


    //检查参数个数的合法性
    //若在命令行输入参数少于3个,则不合法,并给出正确输入方法的提示信息
    if (argc < 3)
    {
        printf("%s <mode num> <target file>\n", argv[0]);//argv[0]指向输入的程序路径及名称。
        exit(0);  //正常运行并退出程序,0返回给操作系统
    }

    //获取命令行参数
    //atoi()函数:将字符串转化为int类型变量
    mode = atoi(argv[1]);
    if ((mode > 777) || (mode < 0))
    {
        printf("mode num error!\n");
        exit(0);
    }

    mode_u = mode / 100;
    mode_g = mode / 10 % 10;
    mode_o = mode % 10;
    mode = (mode_u * 8 * 8) + (mode_g * 8) + mode_o;   //八进制转换
    path = argv[2];


    //int chmod(const char * path, mode_t mode)
    //函数说明:chmod()会依参数mode权限来更改参数path指定文件的权限。
    //更改失败返回-1
    if (chmod(path, mode) == -1)
    {
        perror("chmod error");

        //perror()是错误输出函数,在标准输出设备上输出一个错误信息。
        exit(1);  //非正常运行并退出程序。
    }

    return 0;
}

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值