這個問題在這里已經有了答案: 使用 open()、read() 和 write() 系統呼叫復制檔案 1 個回答 12 小時前關閉。
我正在嘗試cp僅使用讀/寫系統呼叫來實作該命令。
這是我的代碼:
/**
* cp file1 file 2
*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int errsv;
char contents[1024];
int fd_read, fd_write;
fd_read = open(argv[1], O_RDONLY);
if (fd_read == -1)
{
errsv = errno;
printf("Error occured: %d\n", errsv);
}
read(fd_read, contents, sizeof(contents));
fd_write = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0744);
if (fd_write == -1)
{
errsv = errno;
printf("Error occured: %d\n", errsv);
}
write(fd_write, contents, sizeof(contents));
close(fd_read);
close(fd_write);
return 0;
}
我使用以下命令測驗了代碼:
cc test.c
./a.out file1 file2
這是我的檔案1:
dummy text
dummy text
運行代碼后,雖然file2包含來自 的文本file1,但也有一些亂碼。[不要把這個放在這里。]
為什么會這樣?
uj5u.com熱心網友回復:
您需要呼叫read()并write()回圈復制整個檔案。read()當你到達 EOF 時回傳0,或者如果有錯誤,則回傳否定結果,然后你可以結束回圈。
read()回傳讀取的位元組數,可能小于緩沖區的大小。呼叫時需要使用該數字write(),否則會在輸出檔案中寫入額外的字符。這些將在第一次迭代中統一化字符,而在其他迭代中,它們將保留在先前迭代中的字符上。
int main(int argc, char *argv[])
{
char contents[1024];
int fd_read, fd_write;
fd_read = open(argv[1], O_RDONLY);
if (fd_read == -1)
{
perror("open input file");
exit(1);
}
fd_write = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0744);
if (fd_write == -1)
{
perror("open output file");
exit(1)
}
int n_read;
while ((n_read = read(fd_read, contents, sizeof(contents))) > 0) {
write(fd_write, contents, n_read);
}
close(fd_read);
close(fd_write);
return 0;
}
uj5u.com熱心網友回復:
寫(fd_write,內容,strlen(內容));Strlen 回傳填充的條目數,但 sizeof 回傳緩沖區大小,即 1024
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/427875.html
上一篇:如何列印C中陣列中的所有資料?
