I have an image file and I am trying to read 8 bytes of data from the 54th byte of the file and store it in a character array (of size 8 bytes). But upon executing it is only reading 8 bytes even though the pointer has moved 8 bytes ahead from its beginning position (from 54th byte to 62nd byte). When I am trying to print that 1 byte of data which has been successfully retained it is not printing anything.
#include<stdio.h>
int main()
{
FILE *fptr_stego;
FILE *fptr_text;
size_t f_size = 0;
char str[8];
// opening image file
fptr_stego = fopen("stego.bmp", "r");
if(fptr_stego == NULL)
{
printf("FAILED to open stego file\n");
return 0;
}
// opening text file
fptr_text = fopen("decode.txt", "w");
if(fptr_text == NULL)
{
printf("FAILED to open text file\n");
return 0;
}
printf("Successfully opened both files\n");
// shifting pointer to 54th byte
fseek(fptr_stego, 54, SEEK_SET);
printf("File pointer location before reading %ld\n", ftell(fptr_stego));
//read from stego image file
f_size = fread(str, 8, sizeof(char), fptr_stego);
if(f_size != 8)
{
printf("Unable to fetch 8 bytes\n%ld bytes read at %ld position\n", f_size, ftell(fptr_stego));
printf("Data retained: %c\n", str[0]);
return 0;
}
// close files
fclose(fptr_stego);
fclose(fptr_text);
printf("Data read successfull\n");
return 0;
}
Successfully opened both files
File pointer location before reading 54
Unable to fetch 8 bytes1 bytes read at 62 position
Data retained:
This is the output I am getting upon execution. I have checked the image file data using hd stage.bmp command and it has all the data. I have done the encoding in the image file before and at that time it was working perfectly but now when I am trying to decode data from the file this is the issue I am encountering while reading the image file via fread function.
You are confusing two parameters of
fread(), the size of one element and the number of elements.The synopsis of
fread()is:And
fread()returns the number of elements it read.Your call it this way:
fread(str, 8, sizeof(char), fptr_stego);Clearly
8is the requested size of an element, andsizeof (char)is the number of elements. Since the latter is always 1, the return value is 1, too.Swap both values, and all is well:
fread(str, sizeof(char), 8, fptr_stego);