I have this code to copy chunks of 1 KB from a source file to a destination file (practically create a copy of the file) :

test.cpp

#include<stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
int main() {
    int fd = open("file1.mp4", O_RDONLY);
    int fd2 = open("file2.mp4", O_WRONLY | O_CREAT | O_APPEND);
    int nr = 0;int n;
    char buff[1024];
    memset(buff, 0, 1024);

    while((n = read(fd, buff, 1024)) != 0) {
        write(fd2, buff, strlen(buff));
        nr = strlen(buff);
        memset(buff, 0, 1024);
    }

    printf("succes %d %d\n", nr,n);
    close(fd);
    close(fd2);
    return 0;
}

I have tried to copy a .mp4 file, which has 250 MB, but the result has only 77.4 MB. The return value of the last read(), n, is 0, so there isn't supposed to be any error (but it should be, since it doesn't copy entire input file).

I think that the .mp4 file has a EOF byte, which does not actually mean the end of the file. What should I do to be able to copy the entire .mp4 file (I would like an answer to improve my code, not a completely different code).

Thanks for help!

有帮助吗?

解决方案

The problem is that you write strlen(buff) bytes instead of n bytes in your loop.

Whenever the buffer contains a \0 byte, strlen will take it to mean "end of string" and you end up not writing any more. (And when it doesn't contain a \0, you end up reading past the end of the buffer).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top