使用 fwrite 复制文本文件,以垃圾结束? C
Copy textfile using fwrite, ending up with trash? C
我正在尝试将一个文本文件复制到一个新文件中。我在想,如果我想做得聪明,我只需复制所有二进制文件,这样副本就会与第一个相同。但是我在新文档中遇到了奇怪的字符。
#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);
我正在尝试将一个文本文件复制到一个新文件中。我在想,如果我想做得聪明,我只需复制所有二进制文件,这样副本就会与第一个相同。但是我在新文档中遇到了奇怪的字符。
#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);