使用fwrite在C中复制文件

问题描述 投票:1回答:4

我是C的新手,并且正在尝试编写一个程序来复制文件,以便我可以学习文件的基础知识。我的代码将文件作为输入,通过使用fseek和ftell从其末尾减去其开始来计算其长度。然后,它使用fwrite根据我从其手册页得到的内容,将一个数据元素(END - START)元素长写入OUT指向的流,从FI给出的位置获取它们。问题是,虽然它确实产生“复制输出”,但文件与原始文件不同。我究竟做错了什么?我尝试将输入文件读入变量然后从那里写入,但这也没有帮助。我究竟做错了什么?谢谢

int main(int argc, char* argv[])
{ 
    FILE* fi = fopen(argv[1], "r"); //create the input file for reading

    if (fi == NULL)
        return 1; // check file exists

    int start = ftell(fi); // get file start address

    fseek(fi, 0, SEEK_END); // go to end of file

    int end = ftell(fi); // get file end address

    rewind(fi); // go back to file beginning

    FILE* out = fopen("copy output", "w"); // create the output file for writing

    fwrite(fi,end-start,1,out); // write the input file to the output file
}

这有用吗?

{
    FILE* out = fopen("copy output", "w");
    int* buf = malloc(end-start);  fread(buf,end-start,1,fi);
    fwrite(buf,end-start,1,out);
}
c file-io copy fwrite
4个回答
9
投票

这不是fwrite的工作原理。

要复制文件,通常需要分配缓冲区,然后使用fread读取一个数据缓冲区,然后使用fwrite将数据写回。重复,直到您复制整个文件。典型代码就是这个一般顺序:

#define SIZE (1024*1024)

char buffer[SIZE];
size_t bytes;

while (0 < (bytes = fread(buffer, 1, sizeof(buffer), infile)))
    fwrite(buffer, 1, bytes, outfile);

1
投票

fwrite的第一个参数是指向要写入文件的数据的指针,而不是要读取的FILE *。您必须将第一个文件中的数据读入缓冲区,然后将该缓冲区写入输出文件。 http://www.cplusplus.com/reference/cstdio/fwrite/


1
投票

也许通过open-source copy tool in C看你会指向正确的方向。


0
投票

以下是如何做到的:

选项1:动态“数组”

嵌套级别:0

// Variable Definition
char *cpArr;
FILE *fpSourceFile = fopen(<Your_Source_Path>, "rb");
FILE *fpTargetFile = fopen(<Your_Target_Path>, "wb");

// Code Section

// Get The Size Of bits Of The Source File
fseek(fpSourceFile, 0, SEEK_END); // Go To The End Of The File 
cpArr = (char *)malloc(sizeof(*cpArr) * ftell(fpSourceFile)); // Create An Array At That Size
fseek(fpSourceFile, 0, SEEK_SET); // Return The Cursor To The Start

// Read From The Source File - "Copy"
fread(&cpArr, sizeof(cpArr), 1, fpSourceFile);

// Write To The Target File - "Paste"
fwrite(&cpArr, sizeof(cpArr), 1, fpTargetFile);

// Close The Files
fclose(fpSourceFile);
fclose(fpTargetFile);

// Free The Used Memory
free(cpArr);

选项2:Char Char

嵌套级别:1

// Variable Definition
char cTemp;
FILE *fpSourceFile = fopen(<Your_Source_Path>, "rb");
FILE *fpTargetFile = fopen(<Your_Target_Path>, "wb");

// Code Section

// Read From The Source File - "Copy"
while(fread(&cTemp, 1, 1, fpSourceFile) == 1)
{
    // Write To The Target File - "Paste"
    fwrite(&cTemp, 1, 1, fpTargetFile);
}

// Close The Files
fclose(fpSourceFile);
fclose(fpTargetFile);
© www.soinside.com 2019 - 2024. All rights reserved.