【发布时间】:2020-05-31 20:35:36
【问题描述】:
我正在尝试编写一个简单的复制程序。它以 100 个字节为单位读取 test_data.txt,并将这些字节复制到 test_dest.txt。我发现目标文件至少比源文件大一个单位chunk。我如何调整它以便复制正确数量的字节?我需要大小为 1 的复制缓冲区吗?
请注意,重点是使用低级 I/O 系统调用来解决它。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
int main() {
int fh = open("test_data.txt", O_RDONLY);
int trg = open("test_dest.txt", O_CREAT | O_WRONLY);
int BUF_SIZE = 100;
char inp[BUF_SIZE];
int read_bytes = read(fh, inp, BUF_SIZE);
while (read_bytes > 0) {
write(trg, inp, BUF_SIZE);
read_bytes = read(fh, inp, BUF_SIZE);
}
close(trg);
close(fh);
return 0;
}
【问题讨论】:
标签: c