现在的位置: 首页 > 综合 > 正文

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

2013年09月01日 ⁄ 综合 ⁄ 共 1655字 ⁄ 字号 评论关闭

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;   
}

抱歉!评论已关闭.