我正在尝试编写一个简单的复制程序。它读取test_data.txt
100字节的块并将这些字节复制到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;
}
该read
函数只是告诉您读取了多少字节。您应该使用write
该字节数:
write(trg, inp, read_bytes);
另外,您确实应该检查write
通话是否失败。绝对是open
电话。
另外请注意,您只需要一个呼叫即可read
:
ssize_t read_bytes; // The read function is specified by POSIX to return a ssize_t
while ((read_bytes = read(fh, inp, sizeof inp)) > 0)
{
write(trg, inp, read_bytes);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句