函数chown

一、chown 命令

下面以实例简单讲解下 chown 的使用方法。当前登录的账号是 sunbin

  • 创建测试文件

当前 test.txt 文件所有者是sunbin,所属组也是sunbin。

  • 利用 chown 命令修改 test.txt 的所有者和所属组

.可以看到,test.txt 的拥有者变成了 root,所属组变为了root。

 

二、chown函数

1. chown函数原型:

#include <unistd.h>
int chown(const char *pathname, uid_t owner, gid_t group);
                                       若成功,返回0;若出错,返回-1

参数:

  • pathname:要更改的文件名
  • owner:拥有者 uid
  • gropu:所属组 gid

 

需要注意的是,这个函数接受的是 uid 和 gid,而不是以字符串表示的用户名和用户组。所以需要另一个函数getpwnam根据字符串名称来获取 uid 和 gid. 它的原型如下:

 

1. 测试代码:

struct passwd 
{
    char   *pw_name;       // username
    char   *pw_passwd;     // user password
    uid_t   pw_uid;        // user ID
    gid_t   pw_gid;        // group ID
    char   *pw_gecos;      // user information
    char   *pw_dir;        // home directory
    char   *pw_shell;      // shell program
}

struct passwd *getpwnam(const char *name);

 

1. 测试代码:

#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]) 
{
    uid_t uid;
    struct passwd *pwd;
    char *endptr;

    if (argc != 3 || argv[1][0] == '\0') {
        fprintf(stderr, "%s <owner> <file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    uid = strtol(argv[1], &endptr, 10);  /* Allow a numeric string */

    if (*endptr != '\0') {         /* Was not pure numeric string */
        pwd = getpwnam(argv[1]);   /* Try getting UID for username */
        if (pwd == NULL) {
            perror("getpwnam");
            exit(EXIT_FAILURE);
        }
        uid = pwd->pw_uid;
    }

    if (chown(argv[2], uid, -1) == -1) {
        perror("chown");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

输出结果:


 

strtol用法:链接

#include <stdlib.h>
long int strtol(const char *nptr, char **endptr, int base);

测试代码:

#include <stdio.h> 
#include <stdlib.h>

int main()
{
    char buffer[20] = "10379cend$3";
    char *stop;
    printf("%d\n", strtol(buffer, &stop, 2));  //2
    printf("%s\n", stop);
    char a[] = "100";
    char b[] = "100";
    char c[] = "ffff";
    printf("a = %d\n", strtol(a, NULL, 10)); //100
    printf("b = %d\n", strtol(b, NULL, 2));    //4
    printf("c = %d\n", strtol(c, NULL, 16)); //65535
}

输出结果:

 

参考资料

1. 17-chown 函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值