简体   繁体   中英

Reading chunks of data from file (C)

My binary file contains chunks of data in the following format:

0xAA... variable length of bytes... 0XFF

Is there a good way to read these chunks of data directly into a buffer, instead of reading the file one byte at a time?

You Can use "fopen" to open the file "rb" stands for read binary,

 FILE* fileptr;
    unsigned char* buffer;
    fileptr = fopen("file_name", "rb");  // r for read, b for binary

        fseek(fileptr, 0, SEEK_END); // fseek will take fileptr to end of file (SEEK_END)

        filelen = ftell(fileptr); //here we get filelen
        printf("file len =%d\n", filelen);
        rewind(fileptr);

        buffer = (unsigned char*)malloc(filelen * sizeof(unsigned char));
        fread(buffer, filelen, 1, fileptr);
        fclose(fileptr);

finally you will get all your binary file content in buffer pointer.

Don't forget to free buffer after use.

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