复制代码是
curr_size = 0;
fdesc_output = open(path, O_RDWR|O_CREAT|O_TRUNC, 0777);
fdesc_extra_file = open(path2, O_WRONLY|O_CREAT|O_TRUNC,0777);
int lseek_position = lseek(fdesc_output,0,SEEK_SET); // return to the beginning of file
while (curr_size < desired_filesize) { //desired filesize is 100kb
size_t result = read(fdesc_output, buffer, buffer_size);
if (result < 0) {
perror ("Error reading file: ");
exit(1);
}
curr_size+=result;
write(fdesc_extra_file, buffer, buffer_size);
}
答案 0 :(得分:1)
while在102400停止,即100kb(您的desired_filesize
变量)
你应该desired_filesize
更大
或者,不使用desired_filesize:
你可以复制,直到你结束。要在C中获取文件的大小,请在此处阅读How can I get a file's size in C?
如果你想按块(不是逐字节)继续复制,你必须将文件大小分成块,如果你需要制作一个更小的块,最后要小心。
答案 1 :(得分:1)
除非您尝试使用read
和write
来完成目标,否则您可以使用标准C库函数fread
和fwrite
。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
char* sourceFile = argv[1];
char* destinationFile = argv[2];
char buffer[BUFSIZ];
int s;
FILE* in = fopen(sourceFile, "rb");
if ( in == NULL )
{
printf("Unable to open '%s' for reading from.\n", sourceFile);
exit(1);
}
FILE* out = fopen(destinationFile, "wb");
if ( out == NULL )
{
printf("Unable to open '%s' for writing to.\n", destinationFile);
fclose(in);
exit(1);
}
while ( !feof(in) && !ferror(in) )
{
s = fread(buffer, 1, BUFSIZ, in);
if ( s > 0 )
{
s = fwrite(buffer, 1, s, out);
}
}
fclose(out);
fclose(in);
}