Unable to read file using fread in C

I am trying to read the file "file.raw" and 4 bytes at a time to the array and check if it has the specific 4 byte signature that I am looking for. I have problems with this. The value of the result I get is 0, instead of 4 when using fread.

#include<stdint.h> #include<stdio.h> #include<stdlib.h> #include<string.h> typedef uint8_t BYTE; int main(void) { size_t result; FILE *inptr = fopen("file.raw","r+"); //Check if file can be opened. if (inptr == NULL) { printf("File Open Error\n"); return -1; } long int x = 0; while(!feof(inptr)) { // Make space for reading in to an array BYTE *array = (BYTE *) malloc(10); if(array == NULL) { printf("Array Initialization Error\n"); return -1; } result = fread(array,1,4,inptr); //Exit if file not read. ** This is where I can't get past. if(result != 4) { printf("File Read Error\n"); printf("%d\n",result); free(array); fclose(inptr); return -1; } //Compare strings if(memcmp(array,"0xffd8ffe0",4)==0) { printf("File Start found\n"); printf("Exiting...\n"); printf("%p\n",inptr); free(array); fclose(inptr); return 0; } x++; free(array); } printf("%p\n",inptr); printf("%ld\n",x); fclose(inptr); return 0; } 
+4
source share
2 answers

I assume that this will not work on the first iteration of the while , but rather will continue to read the file until you reach the end of the file, after which fread() will return 0 and your program will exit.

The reason he does not find the signature is this:

 memcmp(array,"0xffd8ffe0",4)==0 

This memcmp() call is almost certainly not what you want (it looks for the ASCII character sequence '0' , 'x' , 'f' and 'f' ).

PS As noted in the comments of @Mat, for maximum portability, you should open the file in binary mode ( "r+b" instead of "r+" ).

+4
source

Try opening the file in binary mode ( "r+b" ) instead of text mode ( "r+" ). You probably canceled unintended CRLF conversions by messing up your binary data.

0
source

Source: https://habr.com/ru/post/1389352/


All Articles