Read(),Write()

來源:互聯網
上載者:User

標籤:資料類型   磁碟   err   []   nis   檔案   strong   void   int   

read

read()是一個系統調用函數。用來從一個檔案中,讀取指定長度的資料到 buf 中。

使用read()時需要包含的標頭檔: <unistd.h>

函數原型:

  ssize_t read(int fd, void *buf, size_t count);

  ssize_t是系統標頭檔中 typedef 定義的資料類型,相當於 signed int。

參數:

  fd:要從中讀取內容的檔案的檔案描述符。

  count:期望讀取的檔案位元組數。

傳回值:

  成功 返回讀到的位元組數; 已讀到檔案結尾返回 0; 出錯返回 -1。

 

Write

 write()是一個系統調用函數,作用是將buf 中的內容寫入到檔案中。

使用write()函數時要包含標頭檔 <unistd.h>。

函數原型:

  ssize_t write(int fd, char *buf, size_t count)

參數:

  fd:要從中讀取內容的檔案的檔案描述符。

  count:期望讀取的檔案位元組數。

傳回值:

  寫入成功返回實際寫入的位元組數,出錯返回-1。

  不得不提的是,返回-1的常見原因是:磁碟空間已滿,超過了一個給定進程的檔案長度。    

 

使用read(),write()完成檔案拷貝:

 1  #include <unistd.h> 2  int main(int argc, char *argv[]) 3 { 4    int fs = open(argv[1], O_RDONLY);    //開啟要複製的源檔案 5    if (fs == -1) 6     { 7      perror("open source file"); 8      return -1; 9    }10    int fd = open(argv[1], O_RDONLY | O_CREAT | O_EXCL, 0666);    //建立要複製的目標檔案,若檔案已存在退出11    if (fd < 0)12     {13      perror("open dest file");14      return -1;15    }16 17    char buf[32] = {0};18    int count ;19    while ((count = read(fs, buf, sizeof(buf))) > 0)    //從源檔案讀取資料並寫入目標檔案20    {21      write (fd, buf, strlen(buf));22    }  23    close(fs);24    close(fd);25    return 0;26  }

 

Read(),Write()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.