一、/*用于在当前目录下open或者create系统调用创建一个文件, 然后输出出该文件的类型和组权限位, 并判断该用户对该文件是否有执行权限,如果没有,请通过chmod函数给它加上执行权限。 Gf*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(){
int fd;
struct stat buf;//打开文件,当没有该文件时创建该文件
fd=open("file.txt",O_RDWR|O_CREAT|O_TRUNC,0644);
if(fd<0)
{
printf("Error!/n");
exit(1);
}
else{
if(stat("file.txt",&buf)<0){//把文件信息赋给buf
printf("Getting the file information error/n");
exit(1);
}
else{ //判断文件类型
if(S_ISREG(buf.st_mode))
printf("regular file/n");
else if(S_ISDIR(buf.st_mode))
printf("directory file/n");
else if(S_ISBLK(buf.st_mode))
printf("block special file/n");
else if(S_ISLNK(buf.st_mode))
printf("symbolic link file/n");
else
printf("other file type");
//判断文件的组权限
if(buf.st_mode & S_IRUSR)
printf("read/n");
if(buf.st_mode & S_IWUSR)
printf("write/n");
if(buf.st_mode & S_IXUSR)
printf("execult/n");
else if(chmod("file.txt",buf.st_mode|S_IXUSR)<0)//若没有执行权限,给文件加上
printf("chmod error/n");
else
printf("Added execute permission./n");
}
}
close(fd);
return 1;
}
截图:
截图说明:第一次执行创建了一个file.txt文件,这个文件只有read和write权限,没有execute权限,因此在文件权限中用chmod给文件加入了执行权限。当第二次执行的时候,文件已经有了执行权限。