简体   繁体   中英

Reading a Binary File for Floats and Putting them into an Array

I am reading a binary file for floats and storing them in an array. There is a set of 4 byte floating-point values in the file. However, with my current code, the values of the last two indexes of the array are always read as the same value instead of what the actual value of the last index is. For example, I am getting

array[0] = -123456.123456
array[1] = 123456.123456
array[2] = 123456.123456

when I should be getting something like

array[0] = -123456.123456
array[1] = 123456.123456
array[2] = 654321.654321

I am not sure what I am doing incorrectly in terms of the reading and why I am getting this output.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> 
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <float.h>

int main(int argc, char *argv[]) {
    int fd; 
    float num; 
    size_t nr; 
    int elementnum = 0; 
    
    fd = open(argv[1], O_RDONLY); 
    nr = read(fd, &num, sizeof(float));
    
    if (fd == -1){
        printf("Error opening file");
        exit(1);
    }
    if (nr == -1){
        printf("Error reading file"); 
        exit(1); 
    }
    
    struct stat st; 
    fstat(fd, &st); 
    off_t size = st.st_size; 
    for (int j = 0; j < size/4; j++){
        elementnum++; 
    } 
    printf("number of elements: %d\n", elementnum); 
    
    float array[elementnum];
    for (int i = 0; i < elementnum; i++){
        nr = read(fd, &num, sizeof(float));
        array[i] = num; 
    }

    for (int i = 0; i < elementnum; i++){
        printf("Before Sorting: %f\n", array[i]);
    }
    close(fd);
    return 0; 
}

You need to check the value returned by each read. Since you read one byte out of the file right after you open it (apparently just to validate that one read works) and do not rewind, your loop is trying to read one more value than is available. If you check the read on the final iteration, I suspect you will see that it returns zero. Since it returns 0, it does not change the value of num , so num retains the value it had on the penultimate iteration.

IOW, stop reading a byte after you open. Instead, just open the file and check that open was successful. Then read until read returns 0 or -1. If read returns 0 before you expect it or if it returns -1, then print an error message.

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