c语言实现系统(Linux)文件权限的修改,以及系统文件的创建,写入和读取数据

我们都清楚,在Linux要想修改某个文件的权限,可以执行chmod命令,(4.为读权限,2.为写权限,1.为执行权限)其实我们可以通过编写C程序来实现这一命令,具体

  • chmod实现程序如下:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(int argv,char** argc){//用argc记录命令行参数的个数,字符二维指针记录命令行字符串
    int mode;
    int mode_u;//所有者权限
    int mode_g;//所属组权限
    int mode_o;//其他人权限
    char* path;
    if(argv<3){//验证命令行参数是否合法
        printf("Error mode!\n");
        exit(0);
    }
    mode=(atoi(argc[1]));//将要设置的权限字符串转换成整数,如"777"转换成777
    if(mode>777||mode<0){//验证要设置的权限是否合法
        printf("Error mode!\n"); 
        exit(0);
    }
    path=argc[2];//用一维字符指针通过二维指针argv指向文件名字符串的首地址
    mode_u=mode/100; 
    mode_g=mode/10%10;
    mode_o=mode%10;
    mode=mode_u*8*8+mode_g*8+mode_o;//八进制转换

    if(chmod(mode,path)=-1){//调用chmod函数进行权限修改
        perror("Error mode!\n");
        exit(1);
    }
    return 0;
}
  • 文件的创建:有两种创建方式

    通过调用open函数进行文件的创建
    函数原形如下:

#include<sys/types.h>
#include<sys/fcntl.h>
#include<sys/stat.h>
int open(const char* pathname,int flags);
int open(const char* pathname,int flags,mode_t mode);

简单的实现:

int fd;
//open 1:
if((fd==open("test",O_CREATE|O_EXCL,STRUSR| STWUSR))==-1){
//通过第二个参数可以知道先要在系统中查找文件是否存在,存在的话,提示错误信息
//通过第三个参数可以知道初始会赋予该文件可读可写权限
    perror("open");
}
//open 2:
if((fd=open("test",O_RDWR|O_CREATE|O_TRUNC,S_IRDWR))==-1){
//通过读写方式打开,验证文件是否存在,存在的话写入的数据将覆盖原有数据,不存在的话,
//以读写方式创建文件
    perror("open",__LINE__);
}

通过调用creat函数创建文件

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int creat(comst char *pathname,mode_t mode);//参数第一项为文件名,第二项为权限

实现如下:

int fd;
if((fd=creat("test",S_IRWXU))==-1){
//创建一个文件,如果文件已经存在,则覆盖该文件,给用户赋予文件的读写执行权限。
    perror("Create failed!\n");
}

creat函数与open的不同在于 creat函数创建文件时,只能以只写的方式打开创建的文件,creat无法创建设备文件,这个也不是很常用,一般创建文件时用open函数。

  • 文件指针的移动及向文件写入数据和读取数据
    函数原形:
//write函数
#include<unistd.h>
ssize_t write(int fd,const void *buf,size_t count);
//函数lseek
#include<sys/types.h>
#include<unistd.h>
off_t lseek(int fildes,off_t offset,int whence);
//每一个已经打开的文件,都有一个读写位置,当打开文件时,读写位置通常指向文件开头,文件的读写位置可以由lseek来控制。
lseek(int fildes,0,SEEK_CUR);//将文件指针移动到当前位置
lseek(int fildes,0,SEEK_SET);//将文件指针移动到开始位置
lseek(int fildes,0,SEEK_END);//将文件指针移动到最后位置
//函数read
int fd;
char data[50]="hello world";
if(fd=open("test",O_RDWR|O_CREAT|O_IRWXU)==-1){//先创建文件,并赋予用户读写执行权限
    perror("open",__LINE__);
    }
else{
    printf("Create file success!\n");
}
if((write(fd,data,strlen(data)))!=(strlen(data))){//将数据写入文件,并判断写入的数据长度与要写入数据长度是否相等
    perror("Write failed!\n");
}
//读取文件数据时,应用lseek函数将文件指针移动到文件开始处
int len;
if((len=lseek(fd,0,SEEK_CUR))==-1){
    printf("Error!\n");
}
int ret;
char read_buf[40];
if((ret=read(fd,read_buf,len)<0){//将文件数据全存在read_buf数组里
    printf("Read error!\n");
}
int i;
for(i=0;i<len;i++){//以len为数组的最大遍历限制进行字符数组的遍历
    printf("%c",read_buf[i]);
}
  • 结语:
    linux 文件系统操作生动有趣,还是比较吸引人去探索的!

猜你喜欢

转载自blog.csdn.net/qq_41681241/article/details/81189099
今日推荐