对不起,我的英语不好。我是Linux系统编程的新手,也是C编程的新手。
我正在把一个文件复制到另一个文件,但复制后它们的大小不同。例如,原始文件长112640字节,其副本小10240字节(10kb),只有102400字节。
复制的代码是
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);
}
除非您试图使用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);
}
while停止在102400处,即100kb(您的desired_filesize
变量)
你应该让desired_filesize
变大
或者,不使用desired_filesize:
你可以一直复制到末尾。要在C中获取文件的大小,我如何在C中获取文件的大小?
如果你想继续按块复制(而不是按字节复制),你必须将文件大小分成块,如果你需要制作一个更小的块,最后要小心。