Chmod命令
函数:
Int chmod(const char *path, mode_t mode);
Int fchmod(int fildes, mode_t mode);
Chmod/fchmod的区别在于chmod以文件名作为第一个参数,fchmod以文件描述符作为第一个参数。
参数mode的几种组合:
参数mode数值
字符常量值 | 对应的八进制 | 含义 |
S_IRUSR(S_IREAD) | 00400 | 文件所有者具有可读取权限 |
S_IWUSR(S_IWRITE) | 00200 | 文件所有者具有可写入权限 |
S_IXUSR(S_IEXEC) | 00100 | 文件所有者具有可执行权限 |
S_IRGRP | 00040 | 用户组具有可读取权限 |
S_IWGRP | 00020 | 用户组具有可写入权限 |
S_IXGRP | 00010 | 用户组具有可执行权限 |
S_IROTH | 00004 | 其他用户具有可读取权限 |
S_IWOTH | 00002 | 其他用户具有可写入权限 |
S_IXOTH | 00001 | 其他用户具有可执行权限 |
S_ISUID | 04000 | 文件的(set user-id on execution)位 |
S_ISGID | 02000 | 文件的(set group-ip on execution)位 |
S_ISVTX | 01000 | 文件的sticky位 |
注:上面的数值数字都是八进制
权限更改成功返回0,失败返回-1,错误代码存于系统预定义变量errno中。
实现自己的简单chmod命令
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
//check argu is valid
if(argc< 3)
{
printf("%s<mode num> <target file> \n", argv[0]);
exit(0);
}
intmode; // mode
intmode_u; // user mode
intmode_g; // group mode
intmode_o; // other mode
char*path; // file path
mode= atoi(argv[1]);
if(mode> 777 || mode < 0)
{
printf("modeerror! mode <= 777 && mode >= 0 \n");
exit(0);
}
mode_u= mode / 100;
mode_g= (mode - (mode_u*100)) / 10;
mode_o= mode - (mode_u*100) - (mode_g*10);
//八进制转换
mode= (mode_u * 8 * 8) + (mode_g * 8) + mode_o;
path = argv[2];
if(chmod(path,mode) == -1)
{
perror("chmoderror!");
exit(1);
}
return0;
}
Atoi函数将字符转转换成整形数。如(“777”)的返回值是一个整形数777.