I want to read the 4 first bytes from a binnary file which is a song.wav type. In a .wav file the 4 first bytes must be 52-46-49-49 and I have to read them to check later if they are true.
The thing is that I have a compile arror at the fread line which says invalid conversion from "unsigned char" to "void"
and initialzing argument 1 of 'size_t fread(void*,size_t,size_t,FILE*)
and i dont know what it means.
I saw in a previous topic tha this is the way that fread must be done if i want to read byte by byte. If anyone has any idea of how i can read byte by byte and store them in an array that be great. Thank you.
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 ;
}
ReadAllBytes(String) is an inbuilt File class method that is used to open a specified or created binary file and then reads the contents of the file into a byte array and then closes the file. Syntax: public static byte[] ReadAllBytes (string path);
The open() function opens a file in text format by default. To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable.
It is a single error:
Invalid conversion from
unsigned char
tovoid*
initializing argument 1 ofsize_t fread(void*,size_t,size_t,FILE*)
It means k[i]
is an unsigned char
, and not a pointer. You should use &k[i]
or k+i
.
However, you don't really need to read byte by byte. You can read 4 bytes, no loops involved:
fread(k, 4, 1, myfile);
Printing the numbers:
for (i=0; i<4; i++)
printf("%d\n", k[i]);
In order to read exactly one byte and store it into k
at index i
, you need to provide the address of element i
for(i=0; i<4; i++){
fread(&k[i],1,1,myfile);
}
However, you'd rather read the whole 4 bytes in one go if you're interested in them 4. So no for
loop at all, and just do:
fread(k,1,4,myfile);
It is also good practice to test the return code of fread
(and any I/O operation for that matter) in case it fails. man fread
for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With