Linux 文件讀寫筆記

時間:2015年10月26日
主題:linux文件系統讀寫練習
參考資料:宋敬彬《Linux網絡編程》
系統環境:ubuntu 13.10 + gcc
代碼;

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

/*
安全打開文件
int main(void)
{
    char filename[] = "test.txt";
    int fd = -1;
    fd = open(filename,O_RDWR|O_EXCL|O_CREAT,S_IRWXU);
    if (fd == -1)
    {
        printf("file %s exist!,reopen it \n",filename);
        fd = open(filename,O_RDWR);
        printf("fd : %d \n",fd);
    }
    else
    {
        printf("Open file %s success!,fd: %d \n",filename,fd);
    }
    return 0;
}
*/

#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    int fd=-1;
    char filename[] = "test.txt";
    char buf[] = "another one two check,another song for the radio";
    int size = -1;  
    int i;
    char temp[10];


    fd = open(filename,O_RDWR);
    if (fd == -1)
    {
        printf("file %s is exist !,reopen it  \n",filename);

        fd = open(filename,O_RDWR);
        size = write(fd,buf,strlen(buf));

        printf("write %d bytes into file %s,fd : %d \n",size,filename,fd);

    }
    close (fd);//確保數據已經被保存到文件
    fd = open(filename,O_RDWR);
    //讀出剛剛寫入的數據,看是否正確
    while(size)
    {
        size = 0;
        size = read(fd,temp,10);
        if (size >0 )
        {
            printf("\"");
            for (i=0;i<size;i++)
                printf("%c",temp[i]);
            printf("\"\n");
        }
        else
            printf("reach the end of file %s ,fd is : %d \n",filename,fd);
    }

    return 0;
}

幾點說明:

  1. open()函數的調用必須包含頭文件sys/types.h、sys/stst.h、fcntl.h
  2. open(filename,flag,mode)函數不僅可以打開狹義上的文件,還能打開設備,此時filename代表設備描述符,例如”/dev/sdc”
  3. flag變量和mode變量配合使用可以安全的打開一個文件,通常flag設置爲(O_CREAT|O_RDWR|O_EXCL),而mode僅在O_CREAT有效時才設置。當文件filename不存在時,O_CREAT有效,函數會新建一個mode權限的文件,如果此時filename文件存在,該函數在執行時會報錯,即通過O_EXCL和O_CREAT同時設置時函數的返回值,來檢測文件是否存在,如果在文件存在的條件下設置O_CREAT,則函數會返回-1,如果文件不存在而設置O_CREAT,則會按照參數指定的格式創建文件。
  4. 關於文件描符,linux系統保留0(標準輸入)、1(標準輸出)、2(標準錯誤)三個編號,而文件描述符則從3開始遞增。如果不正常關閉已經打開的文件,則該序號會一直遞增直到1023(最大值)。
  5. read(fd,buf,count)函數使用必須包含頭文件unidtd.h。如果達到文件末尾,函數返回0。如果讀入的數據不大於緩衝區大小則返回實際讀到的字節數;否則,返回緩衝區大小,但是緩衝區內的數據截斷後的數據。
  6. write()函數與read()函數類似,只是函數執行後,數據只是寫到緩衝區而不是真正的文件,可以調用fsync()將數據寫入設備。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章