1. 程式人生 > >c語言實現系統(Linux)檔案許可權的修改,以及系統檔案的建立,寫入和讀取資料

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 檔案系統操作生動有趣,還是比較吸引人去探索的!