文件管理--改变文件所有者

1.相关函数说明

 

#include<sys/types.h>
#include<unistd.h>
定义函数 int chown(const char * path, uid_t owner,gid_t group);
函数说明 chown()会将参数path指定文件的所有者变更为参数owner代表的用户,而将该文件的组变更为参数group组。如果参数owner或group为-1,对应的所有者或组不会有所改变。root与文件所有者皆可改变文件组,但所有者必须是参数group组的成员。当root用chown() 改变文件所有者或组时,该文件若具有S_ISUID或S_ISGID权限,则会清除此权限位,此外如果具有S_ISGID权限但不具S_IXGRP位,则该文件会被强制锁定,文件模式会保留。
返回值 成功则返回0,失败返回-1,错误原因存于errno。
错误代码 参考chmod()。

 

2.范例

 

//chmod.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>

int main(void)
{
    struct stat statbuf;
   
    if(stat("test.txt", &statbuf) == -1){ /* 为改变所有者前文件的状态 */
        perror("fail to get status");
        exit(1);   
    }
   
    printf("before changing owner/n"); /* 打印文件的所有者用户ID和组ID */
    printf("the owner of test.txt is : %d/n", (unsigned int)statbuf.st_uid);
    printf("the group of test.txt is : %d/n", (unsigned int)statbuf.st_gid);
    printf("/n");
   
    if(chown("test.txt", 0, -1) == -1){ /* 将文件的所有者修改为根用户,不改变组用户ID */
        perror("fail to change owner");
        exit(1);   
    }
   
    if(stat("test.txt", &statbuf) == -1){ /* 再次取得文件的状态信息 */
        perror("fail to get status");
        exit(1);   
    }
   
    printf("after changing owner/n");
    printf("the owner of test.txt is : %d/n", (unsigned int)statbuf.st_uid); /* 输出结果 */
    printf("the group of test.txt is : %d/n", (unsigned int)statbuf.st_gid);
    printf("/n");
   
    if(chown("test.txt", 100, -1) == -1){ /* 将文件的所有者修改改为一个根本不存在的用户 */
        perror("fail to change owner");
        exit(1);   
    }
   
    if(stat("test.txt", &statbuf) == -1){ /* 得到文件状态信息 */
        perror("fail to get status");
        exit(1);   
    }
   
    printf("nonexsit owner/n");
    printf("the owner of test.txt is : %d/n", (unsigned int)statbuf.st_uid); /* 输出结果 */
    printf("the group of test.txt is : %d/n", (unsigned int)statbuf.st_gid);
   
    return 0;   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值