gpt4 book ai didi

c - C 中的 fgetc 和 fputc

转载 作者:行者123 更新时间:2023-11-30 15:16:13 25 4
gpt4 key购买 nike

我试图从一个文件的开头复制 5 个字节并将它们放入另一个文件的开头。然而,他们并没有准确地复制。我认为问题出在 fputc 和 fgetc 上,但不确定是什么......

bmpFile = fopen("frog.bmp", "rb");
encodedFile = fopen("encodedFrog.bmp", "rwb");

for (int i=0; i<5; i++){
fputc(fgetc(bmpFile), encodedFile); //copy that byte, unchanged into the output
}

//close and open both files, read the first 5bytes back;
fclose(bmpFile);
fclose(encodedFile);
bmpFile = fopen("frog.bmp", "rb");
encodedFile = fopen("encodedFrog.bmp", "rwb");
for (int i=0; i<5; i++){
unsigned int actual = fgetc(bmpFile);
unsigned int value = fgetc(encodedFile);
printf("actual: %d \tvalue: %d\n", actual, value);
}

结果是:

actual: 66  value: 66
actual: 77 value: 77
actual: 54 value: 134
actual: 115 value: 68
actual: 20 value: 17

谢谢

最佳答案

"rwb" 不是有效的 fopen 模式。您可能想使用

fopen("encodedFrog.bmp", "r+b");

这将打开现有文件以二进制模式进行输入和输出。如果文件不存在,则应使用"w+b"

fopen("encodedFrog.bmp", "w+b");

这将打开一个新文件,用于以二进制模式输入和输出。

此外,正如 @amdixon 提到的,您应该使用 rewind,而不是重新打开文件,这会将流位置重置到开头。

关于c - C 中的 fgetc 和 fputc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com