unix環境進階編程——read(),write()

來源:互聯網
上載者:User

標籤:

1.read函數調用read函數從檔案去讀資料,函數定義如下:[cpp] view plaincopy
  1. #include <unistd.h>  
  2. ssize_t read(int filedes, void* buff, size_t nbytes);  
第一個變數代表檔案描述符,如果是標準輸入STDIN_FILENO第二個變數代表從檔案中讀進buff數組中第三個變數指的是要讀進來的字元個數成功則返回實際讀取的byte數,如果已經達到檔案結尾則返回0,出錯則返回-1.
#include <fcntl.h>#include <stdio.h>int main(void){int fd;char w[100];char r[100];fd = open("./a.txt", O_RDWR|O_EXCL, S_IRUSR|S_IWUSR|S_IXUSR);int r1 = read(fd,r,10);printf("%d",fd);printf("%s",r);return 0;}
以上代表把a.txt中的前十個字元讀進r數組。

2.write函數調用write函數向開啟的檔案寫入資料,函數定義如下:[cpp] view plaincopy
  1. #include <unistd.h>  
  2. ssize_t write(int filedes, void* buff, size_t nbytes);  
第一個變數代表檔案描述符,如果是標準輸入STDOUT_FILENO第二個變數代表把buff中的內容寫入,第一個參數中的檔案第三個變數指的是要寫進來的字元個數成功則返回實際寫入的byte數,出錯則返回-1.
#include <fcntl.h>#include <stdio.h>#include <unistd.h>int main(void){int fd;char w[100];char r[100];fd = open("./a.txt", O_RDWR|O_EXCL, S_IRUSR|S_IWUSR|S_IXUSR);int r1 = read(fd,r,10);write(STDOUT_FILENO,r,10);//printf("%d",fd);//printf("%s",r);return 0;}
以上代碼上將從a.txt中讀進來的內容,寫入標準輸出,也就是控制台上。


unix環境進階編程——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.