创建文件,并输出文件类型和组权限

 一、/*用于在当前目录下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给文件加入了执行权限。当第二次执行的时候,文件已经有了执行权限。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值