user1950241
user1950241

Reputation: 13

Binary reading returning zero

I'm trying to read a binary file and display its contents in the terminal, but this line of code:

size_t readed = fread(buffer, sizeof(buffer), positionX, file);

It is returning zero, so my loop is stopped, what is the suggestion to solve this problem?

buffer = Storage
sizeof(buffer) = Size File
positionX = 7918080 <-- Dynamic Pointer
file = File to read

Terminal output:

https://i.sstatic.net/i9pls.png

My complete code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage: Please insert the file to read\n");
        return 1;
    }
    else
    {
        FILE *file;

        file = fopen(argv[1], "rb");

        //Cannot open file --> check pointer file after fopen
        if (file == NULL)
        {
            printf("Cannot open file \n");
            exit(0);
        }

        long positionX = ftell(file);

        printf("Pointer at the beginning %ld\n", positionX);

        fseek(file, 0, SEEK_END);

        positionX = ftell(file);

        rewind (file); // Sets the position indicator associated with stream to the beginning of the file

        unsigned char buffer[positionX]; // o buffer deveria ser criado aqui depois de pegar a posição final

        printf("Pointer at the End: %ld\n", positionX);

        // Read the content --> it's always good to check the read value
        // the third parameter was 1, it should be "position"
        size_t readed = fread(buffer, sizeof(buffer), positionX, file);

        printf("the size is %zu\n", readed);  // decimal size_t ("u" for unsigned)
        printf("the size is %zx\n", readed);  // hex size_t

        for(size_t i = 0; i < readed; i++) // usar readed como limite
        {
            printf("%x ", buffer[i]); // prints a series of bytes
        }
    }
}

Thanks

Upvotes: 1

Views: 379

Answers (1)

dbush
dbush

Reputation: 223689

Your call to fread is incorrect:

size_t readed = fread(buffer, sizeof(buffer), positionX, file);

The second parameter is the size of each element to read, and the third is the number of elements. This means that you're attempting to read up to sizeof(buffer) * positionX bytes, but buffer isn't that big. As a result, you write past the end of the buffer triggering undefined behavior.

Since you're reading positionX individual characters, you want 1 for the member size:

size_t readed = fread(buffer, 1, positionX, file);

Upvotes: 2

Related Questions