Reputation: 101
I am trying to read a binary file and its content.
/*aoObj.fb is the pointer of the file (e.x. FILE *fp)*/
char ch;
aoObj.fp = fopen(aoObj.f_name, "rb");
if (aoObj.fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
/* /\*list all strings *\/ */
printf("\n\nThe content of the file: \n");
while ((ch = fgetc(aoObj.fp)) != EOF)
printf("%c", ch);
fclose(aoObj.fp);
(void) opt_free(&aoObj);
return 0;
}
But I am facing issues when I print the content of thi file because only the first character of the input isn't printed ok, as follows:
May I know why this is happening ?
EDIT: All the variables which are being read are declared as STRINGS
Upvotes: 1
Views: 435
Reputation: 16540
The OP states the file contents are 'binary' not 'text' Therefore, accessing the file should be via the I/O operators made for binary files,
Suggest:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Since the data read from the 'binary' file is NOT ascii characters, it is an 'error' to try to print those 'binary' characters with the 'output format conversion' specifier: %c
.
Suggest:
printf( "%02x\n", ch );
Note: the %02x
so a leading nibble of 0x0 will be printed rather than suppressed.
When the code is corrected to use: fread()
rather than fgetc()
the declaration of ch
can/should be unsigned char ch;
so no need to change that to int ch;
The following proposed code:
main()
function and the passing of the parameter: f_name
so does not linkfread()
to 'assume' EOF, however, it may be instructive (and for robust code) to check the value of errno
just to assure there was no other error.Note: the proposed code is not very efficient as it only reads a single byte at a time rather than a whole buffer full of bytes
Note: the proposed code will output one byte contents (in hex) on a single line. You might want to modify that to output several bytes contents (in hex) before moving to a new line.
and now, the proposed code:
#include <stdio.h> // FILE, fopen(), perror(), printf(), fclose()
// fread()
#include <stdlib.h> // exit(), EXIT_FAILURE
void myfunc( char *f_name )
{
unsigned char ch;
FILE *fp = fopen( f_name, "rb");
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
/* /\*list all strings *\/ */
printf("\n\nThe content of the file: \n");
size_t bytesRead;
while ( ( bytesRead = fread( &ch, 1, 1, fp ) ) == 1 )
{
printf("%02x\n", ch);
}
fclose(fp);
}
Upvotes: 2