一、函數
size_t read(int fd, void *buf, size_t count);
功能:從檔案fd中期望讀取count位元組的資料存儲到buf内
參數:count:期望讀取的位元組數
傳回:成功讀取的位元組數,0檔案末尾,-1出錯
ssize_t write(int fd, const void *buf, size_t count);
功能:将buf裡的資料寫到檔案fd中,大小為count位元組
傳回:成功寫入的位元組數,失敗-1
二、測試源碼
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define N 32
int main(int argc, const char *argv[])
{
int fd_r = open(argv[1], O_RDONLY);
if(fd_r == -1)
{
printf("open error\n");
return -1;
}
int fd_w = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0664);
if(fd_w == -1)
{
printf("open error\n");
return -1;
}
char buf[N];
int ret = 0;
while((ret = read(fd_r, buf, N)) > 0)
{
write(fd_w, buf, ret);
}
printf("copy ok\n");
close(fd_r);
close(fd_w);
return 0;
}
三、測試結果

四、關鍵代碼分析
while((ret = read(fd_r, buf, N)) > 0)
{
write(fd_w, buf, ret);
}
當沒有讀到檔案的末尾時,将buf中的資料通過write寫入到待拷貝的檔案中,直到讀到檔案末尾。