如何不写比C缓冲区更多的字节?

TMOTTM

我正在尝试编写一个简单的复制程序。它读取test_data.txt100字节的块并将这些字节复制到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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章