標籤:資料類型 磁碟 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()