I am writing a program to read a hex image file, and write a part of it to another file.
When I read it, some part of the file is read properly, but somewhere in between it starts reading and returning FF instead of actual hex data on and off in the file.
I have used unsigned char ch
for ch=fgetc(sourceImageFile)
I don't understand where I'm going wrong, and why it's returning long lines of FF in between. Please Help Me. Also I've kept one input file as .txt to be able to open it and debug.
This is my code:
#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;
}
Just paraphrasing what @kaylum already told you. fgetc()
returns an int
while you are storing the result in a unsigned char
. This means you cannot tell from ch
if you read 0xff
or EOF (EOF is defined as -1 on my system, and in 2's complement that is 0xff
). As you are processing binary data you want to change the type. Always check the return value!
int ch;
...
if((ch = fgetc(source)) == EOF) {
// nothing more to read
}