Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read byte by byte from a file

Tags:

c

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 ;
}
like image 358
Zisis Diamantis Avatar asked Jun 28 '13 10:06

Zisis Diamantis


People also ask

How do I read bytes from a file?

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);

How do I read a binary file in Python?

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.


2 Answers

It is a single error:

Invalid conversion from unsigned charto void* initializing argument 1 of

size_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]);
like image 168
Elazar Avatar answered Oct 21 '22 16:10

Elazar


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.

like image 32
rectummelancolique Avatar answered Oct 21 '22 15:10

rectummelancolique