[英]How to not write more bytes than are in the buffer in C?
我正在尝试编写一个简单的复制程序。 它以 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;
}
read
的 function 只是告诉你它读取了多少字节。 您应该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);
}
您的代码不是标准的 C11。 通过阅读标准n1570 进行检查,并在现代 C书之前阅读。
您的代码或多或少是POSIX ,并且肯定可以在大多数 Linux 发行版上编译,例如Debian或Ubuntu元数据包(您想安装它们的build-essentials
)
请阅读open(2 )、 read(2) 、 write(2) 、您正在使用的每个syscall(2)以及errno(3)的文档。
请注意,您调用的每个函数都可能失败,您的代码应该测试失败案例。 另请注意,在某些情况下, write
(或read
)可能是部分的,这已记录在案。
with a recent GCC -the usual C compiler on most Linux distributions, compile with all warnings and debug info, so gcc -Wall -Wextra -g
.
学习使用 GDB 调试器。
阅读有关构建自动化工具的信息,例如GNU make (在大多数 Linux 系统上非常常见的工具)或ninja 。
请注意strace(1) 。 您可以在cp(1)上使用它,或者研究GNU coreutils的源代码(提供cp
)。
请记住,大多数 Linux 发行版大多由开源软件组成。
我什至认为你应该研究他们的源代码,至少是为了获得灵感!
我正在尝试编写一个简单的复制程序。 它以 100 个字节为单位读取 test_data.txt 并将这些字节复制到 test_dest.txt
如果性能很重要,那么 100 字节的块大小在实践中确实太小了。 我会推荐两个大于 4Kbytes 的幂(x86-64 上通常的页面大小)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.