简体   繁体   中英

Reading file of binary integers in C using open() and read()

I am trying to read a binary file containing integers in the binary form. I need to use the open() and read() functions rather than fopen() and the like.

I open my file and try to read it, but i get binary symbols in my output.

char buffer[sizeof(int)];
int file1;
int bytesRead;
file1 = open(argv[1], O_RDONLY);
    if(file1 == -1)
    {
        printf("unable to open file\n");
        exit(1);
    }
    while((bytesRead = read(file1, &buffer, sizeof(buffer))))
    {
        printf("%d\n", buffer);
    }

Can anyone point me in the right direction?

Error 1: read(file1, &buffer, sizeof(buffer)

When you use an array, then you need not pass it address to the "read" call.

Correction :
read(file1, buffer, sizeof(buffer);


Error 2 :  
while((bytesRead = read(file1, &buffer, sizeof(buffer))))
Correction : 
while((bytesRead = read(file1, &buffer, sizeof(buffer))) >= 0)

The while loop will evaluate to true even if the read call fails, since it returns -1 on
failure which means true. It returns 0 when there's nothing left to read, you can apply a check on that to
indicating that there's nothing more tobe read.

Variables should be declared with the type they are used as:

int buffer;

If you want an int , declare an int . This is an oversimplification, but this way you're safe against strict-aliasing violations. If only this line is changed, the other code is fine.


The original

char buffer[sizeof(int)];

has the drawback, that it's impossible to read it as an int without violating strict-aliasing *) (strict-aliasing means, you mustn't access an object through an lvalue with a wrong type—in short, that is, different from the declared one).

The behaviour of

printf("%d\n", buffer);

is undefined, a value of type char * is passed to printf where an int is expected. (This line is OK if buffer is an int ; and it should be declared as an int , since it is read as an int .)

If a char array was really what is intended, the line

while((bytesRead = read(file1, &buffer, sizeof(buffer))))

would be unusual: Arrays decay to pointers when passed to a function, there's no need to use the address operator & . (But it's needed if buffer is of type int .)

*) Not entirely impossible, you could type-pun with a union .

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