简体   繁体   中英

How to read Binary Files using command line argument and print it out in C?

So Ive got a struct of

struct records {
    short link; 
    double gate; 
    unsigned char bar;
    int rest; 
    char rink; 
};

And now I want to read binary inputs and print them out using fread() . I'm just having trouble figuring out what exactly to do.

So I've only got

int main(int argc, char* argv[]){
}

So first off, how do you open a binary file? All the examples I've seen online only use main() and when using fopen() they always specify the input. How to use the command line arguments to specify which file to open?

And then, how do I read those files into the struct I've created and print them out?

Any help appreciated, thank you so much.

Provide the name of the binary file as argument when you run the program.

argv[0] will be the name of the program itself and the name of the file in argv[1] .

As Jonathan mentioned in the comment, you must ensure that argv[1] actually exists before you access it or it will cause error.

Something like

if(argc<2)
{
    printf("\nError");
    return -1;
}

should take care of that.

Then do

FILE *fin=fopen(argv[1], "rb");

and then use fread() to read from the file.

The second argument of fopen() is the mode in which file is opened. r and b in "rb" means read and binary respectively.

As for fread() , first create a variable, say a of type struct records .

Then use

fread(&a, sizeof(a), 1, fin);

Here we pass address of a so that the read data will be stored there. sizeof(a) says the size of each block read by fread() and the 1 is the number of blocks that should be read.

fread() will return the number of blocks that were read successfully which in our case is 1 . If the number of blocks that we asked to be read and the number of blocks that were actually read are not same, either the file ended or some error occurred.

Afterwards we can access each element of a .

https://www.tutorialspoint.com/c_standard_library/c_function_fread.htm http://pubs.opengroup.org/onlinepubs/009695399/functions/fread.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM