Linux系統編程_2_檔案I/O

來源:互聯網
上載者:User

標籤:linux編程   檔案io   

這裡說的的檔案I/O指的是不帶緩衝的;

1.關於帶緩衝的IO操作和不帶緩衝的IO操作,參見另一篇文章:

帶緩衝IO和不帶緩衝IO詳解


Linux中的檔案IO(不帶緩衝的IO)通常用的有以下幾個:

open    read    write    lseek   close


2.open的參數

int fd(filename, mode);

mode 通常可以是O_RDONLY(唯讀)  O_WRONLY(唯寫)  O_RDWR(讀寫) 必須指定且只能指定一個!

其他的可供選擇,可通過或運算添加:O_APPEND  O_CREAT  O_EXCL   O_TRUNC


3.read與write在讀取網路資料時,可能由於網路的緩衝機制等造成實際讀到的資料小於應讀資料。


4.用lseek實現擷取檔案大小的功能:

1 #include <stdio.h>2 #include <unistd.h>3 #include <fcntl.h>4 #include <stdlib.h>56 int main(int argc, char ** argv)7 {8     off_t size;9     int nFd;1011     if(argc < 2)12     {13         printf("Usage: ./size xxx\n");14         exit(-1);15     }1617     nFd = open(argv[1], O_RDONLY); 18     if(-1 == nFd)19     {20         perror("Open file error");21         exit(-1);22     }23     size = lseek(nFd, 0, SEEK_END);24     printf("The file size is : %d\n", size);2526     return 0;27 }

5.dup與dup2函數,都用來複製一個現存的檔案描述符

int dup(int fd);

int dup2(int fd1,int fd2);//若 fd2已經開啟,則先關閉


6.sync  fsync  fdatasync函數都可以用來將緩衝區中的資料重新整理到物理磁碟

sync函數並不等待實際的寫磁碟操作結束後返回。

fsync函數等待寫磁碟操作結束後返回,可以用於資料庫這樣的應用程式。


7.fcntl函數——可以改變已經開啟的我檔案的性質

#include <fcntl.h>

int fcntl(int fd, int cmd, int arg);

fcntl函數有五種功能:

1.複製一個現有的檔案描述符(cmd=F_DUPFD)

2.擷取/設定檔案描述符(cmd=F_GETFD / cmd=F_SETFD

3.擷取/設定檔案狀態(cmd=F_GETFL / cmd =F_SETFL)

4.擷取/設定非同步IO所有權(cmd=F_GETOWN / cmd=F_SETOWN)

5.擷取/設定檔案記錄鎖(cmd=F_GETLK / cmd=F_SETLK/F_SETLKW)




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.