天天看點

Linux檔案系統相關操作

C檔案I/O

在C語言中,預設會打開三個輸入輸出流,分别是stdin,stdout,stderr,不難發現,這三個流的類型都是FILE*,通過fopen得到的傳回值為檔案指針,指向打開的檔案

#include <stdio.h>
#include <string.h>

int main(){

    FILE* fp = fopen("myfile","w");
    if(fp == NULL){
        perror("fopen error\n");
    }

    const char* msg = "Hello fp\n";
    int count = 5;
    while(count--){
        fwrite(msg,strlen(msg),1,fp);
    }
    fclose(fp);

    return 0;
}
           

系統檔案I/O

操作檔案,當然不止有上述的C接口或者其他語言的一些接口,我們還可以通過系統所暴露的接口來進行檔案通路,例如

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int main(){
    int fd = open("myfile",O_WRONLY|O_CREAT,0644);
    if(fd < 0 ){
        perror("open");
        return 1;
    }

    int count = 5;
    const char* msg = "hello fd\n";
    int len = strlen(msg);

    while (count--){
        write(fd,msg,len);
    }
    close(fd);
    return 0;
}
           

open函數:int open(const char* pathname , int flags);

                int open(const char* pathname, int flags, mode_t mode);

pathname:要打開或建立的目标檔案

flags:   打開檔案時,可以傳入多個參數選項,用一個或多個常量進行“或”運算,構成了flag

參數:

        O_RDONLY:隻讀打開

        O_WRONLY:隻寫打開

        O_RDWR    :讀寫打開

                          上面的三個變量必須指定一個且隻能指定其中一個

        O_CREAT   :若檔案不存在,則建立它。需要使用mode選項,來指明檔案的通路權限

        O_APPEND :追加寫檔案

傳回值:

        成功:傳回的事新打開的檔案描述符

        失敗:傳回-1;

mode_t:設定權限

open函數具體使用哪一個和應用場景有關,如果目标檔案不存在,需要open建立,則第三個參數表示建立函數的預設權限,否則,使用兩個參數的open。

檔案描述符fd

了解了open函數之後,又引出了一個新的概念,檔案描述符

繼續閱讀