How to read byte byte from file

I want to read the first 4 bytes from a binary file, which is a type of song.wav. In the .wav file, the first 4 bytes should be 52-46-49-49, and I should read them later if they are correct.

The thing is, I have a compiler in the fread line that says invalid conversion from "unsigned char" to "void" and initialzing argument 1 of 'size_t fread(void*,size_t,size_t,FILE*) , and I don't know what that means.

In the previous section, I saw how this is done if you need to read byte by byte. If anyone knows how I can read bytes by bytes and store them in an array that will be large. Thanks.

 void checksong(char *argv[]){ FILE *myfile; int i; unsigned char k[4]; myfile=fopen(argv[2],"r"); i=0; for(i=0; i<4; i++){ fread(k[i],1,1,myfile); } for(i=0; i<4; i++){ printf("%c\n", k[i]); } return ; } 
+6
source share
4 answers

This is the only error:

Incorrect conversion from unsigned char to void* initialization argument 1 of

 size_t fread(void*,size_t,size_t,FILE*) 

This means that k[i] is an unsigned char , not a pointer. You must use &k[i] or k+i .

However, you do not need to read byte by byte. You can read 4 bytes, without any loops:

 fread(k, 4, 1, myfile); 

Printing numbers:

 for (i=0; i<4; i++) printf("%d\n", k[i]); 
+10
source

To read exactly one byte and store it in k at index i , you need to specify the address of element i

 for(i=0; i<4; i++){ fread(&k[i],1,1,myfile); } 

However, you'd better read just 4 bytes at a time if you are interested in them. 4. There is no for loop at all and just do:

 fread(k,1,4,myfile); 

It's also a good idea to check the fread return code (and any I / O, for that matter) if it fails. man fread for more information.

+5
source

You can use only

 char buffer[4]; fread(buffer,1,4,myfile); 
+4
source

you don't need to use fread() Even fgetc() works well. Simple coding. SImple as reading a text file.

 #include <stdio.h> int main(int argc, char** argv) { FILE* f = fopen("lak", "rb"); fseek(f,0,SEEK_END); long lsize=0,i=0; lsize = ftell(f); rewind(f); while(i<lsize){ int first = fgetc(f); i++; printf("first byte = %x\n", (unsigned)first); //you can do anything with //first now } fclose(f); return 0; } 
0
source

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


All Articles