I want to copy the data from one file to other. But only one byte is copying.
我想把数据从一个文件复制到另一个文件。但只有一个字节在复制。
#include<stdio.h>
void main() {
FILE *fp1, *fp2;
char a;
fp1 = fopen("test.jpg", "r");
if (fp1 == NULL) {
puts("cannot open this file");
exit(1);
}
fp2 = fopen("test1.jpg", "w+");
if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
do {
a = fgetc(fp1);
fputc(a, fp2);
} while (a != EOF);
fcloseall();
}
test.jpg consists of data ff d8 32 86 ..... But it is copying only ff and coming out of the while loop. Is i am doing any thing wrong
test.jpg包含数据ff d832 86……但它只是复制ff,从while循环中跳出来。我做错什么了吗?
1 个解决方案
#1
3
Declare a
as int
, not char
.
声明a为int,而不是char。
int a;
Otherwise, that first 0xFF
gets expanded into -1
(EOF
).
否则,第一个0xFF将扩展为-1 (EOF)。
You should also open/close the files with b
(for "binary"):
您还应该打开/关闭带有b的文件(用于“二进制”):
fp1 = fopen("test.jpg", "rb");
// ...
fp2 = fopen("test1.jpg", "w+b");
And, as Drew noted, check EOF
before writing the character:
而且,正如Drew所指出的,在写这个角色之前要检查EOF:
while ((a = fgetc(fp1)) != EOF) {
fputc(a, fp2);
}
#1
3
Declare a
as int
, not char
.
声明a为int,而不是char。
int a;
Otherwise, that first 0xFF
gets expanded into -1
(EOF
).
否则,第一个0xFF将扩展为-1 (EOF)。
You should also open/close the files with b
(for "binary"):
您还应该打开/关闭带有b的文件(用于“二进制”):
fp1 = fopen("test.jpg", "rb");
// ...
fp2 = fopen("test1.jpg", "w+b");
And, as Drew noted, check EOF
before writing the character:
而且,正如Drew所指出的,在写这个角色之前要检查EOF:
while ((a = fgetc(fp1)) != EOF) {
fputc(a, fp2);
}