【发布时间】:2021-06-26 06:47:15
【问题描述】:
我正在编写一个程序来读取一个十六进制图像文件,并将其中的一部分写入另一个文件。
当我读取它时,文件的某些部分被正确读取,但介于两者之间的某个位置开始读取并返回 FF,而不是在文件中打开和关闭实际的十六进制数据。
我已将unsigned char ch 用于ch=fgetc(sourceImageFile)
我不明白我哪里出错了,以及为什么它在两者之间返回长行 FF。请帮我。 此外,我将一个输入文件保存为 .txt,以便能够打开它并进行调试。
这是我的代码:
#include<stdio.h>
#include<string.h>
int main()
{
FILE* source;
FILE* sr, * sg, * sb;
int i = 1;
source = fopen("file.L-4", "r");
sr = fopen("red.img", "wb+");
sg = fopen("green.img", "wb+");
sb = fopen("blue.txt", "wb+");
fseek(source, 540, SEEK_SET);
printf("\nDone phew!\n");
unsigned char ch;
int l = 1;
unsigned char buf[10];
while (l <= 5279)
{
fseek(source, 32, SEEK_CUR);
i = 1;
while (i <= 4919 && l < 5280)
{
ch = fgetc(source);
sprintf(buf, "%02x ", ch);
fputs(buf, sb);
i++;
} //BLUE done
l++;
//fseek(source,9902,SEEK_CUR);
fseek(source, 32, SEEK_CUR);
i = 1;
while (i <= 4919 && l < 5280)
{
ch = fgetc(source);
sprintf(buf, "%02x ", ch);
fputs(buf, sg);
i++;
} //GREEEN done
l++;
fseek(source, 32, SEEK_CUR);
i = 1;
while (i <= 4919 && l < 5280)
{
ch = fgetc(source);
sprintf(buf, "%02x ", ch);
fputs(buf, sr);
i++;
} //RED done
l++;
//printf("%d ",l);
}
printf("\nthis is done too!\n");
fclose(sr);
fclose(sg);
fclose(sb);
fclose(source);
return 0;
}
【问题讨论】:
-
fgetc返回int而不是char。这是因为它返回EOF表示文件结束或错误。EOF通常是-1或所有Fs。您到处都有幻数,这不仅是非常糟糕的编码形式,而且可能导致读取文件末尾。检查获得EOF时的读取偏移量。 -
你应该正确地格式化你的代码。很难处理格式不正确的代码。
-
并将其最小化,这样我们就不会花时间查看有效的东西。
-
谢谢,我会处理的。
标签: c image image-processing computer-science ff