我正在尝试将文本文件复制到新文件。我在想,如果我想做得聪明,我只需复制所有二进制文件,这样副本将与第一个副本相同。然而,我最终在新文档中得到了奇怪的字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char * argv[])
{
FILE * fporgi, * fpcopy;
if((fporgi = fopen(argv[1], "rb")) == NULL){
//Error checking
fprintf(stdout, "Error occurred trying to open file :%s", argv[1]);
exit(EXIT_FAILURE);
}
if((fpcopy = fopen(argv[2], "wb")) == NULL){
fprintf(stdout, "Error occurred trying to open file :%s", argv[2]);
exit(EXIT_FAILURE);
}
long bytes;
fseek(fporgi, 0L, SEEK_END);
bytes = ftell(fporgi);
fprintf(stdout, "\n%ld\n", bytes);
unsigned char buffer[bytes];
fprintf(stdout, "\n%u\n", sizeof(buffer));
fread(buffer, sizeof(buffer), 1, fporgi);
fwrite(buffer, sizeof(buffer), 1, fpcopy);
fclose(fporgi);
fclose(fpcopy);
return 0;
}
例如,如果原始文件包含“hej svej”,则新文件将包含:“(œÌuR0@NUL”
最佳答案
读取长度后,您需要返回到文件的开头:
fseek(fporgi, 0L, SEEK_END);
bytes = ftell(fporgi);
fprintf(stdout, "\n%ld\n", bytes);
fseek(fporgi, 0L, SEEK_SET);
关于使用 fwrite 复制文本文件,结果是垃圾? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28954829/