Cesar Morais
Cesar Morais

Reputation: 1

Why is fread reading absurd numbers?

I wish to read a file containing 5 numbers on each line and put a every number into an array, for example:

FILE: 1 2 3 4 5 | ARRAYS: a[1] = 1, a[1] = 2, a[2] = 3, etc.

However, when I try exactly this file with the code below

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

int main ()
{
    char nomeDoArquivo[100];
    int iter, teste[5];

    fgets(nomeDoArquivo, 100, stdin);
    nomeDoArquivo[strlen(nomeDoArquivo) - 1] = '\0';

    FILE *f = fopen (nomeDoArquivo, "rb");
    if (f == NULL) 
        exit (1);

    for (int a = 0; a < 5; a++) {
        int buffer [5];
        fread(&buffer[a], sizeof(int), 1, f);
        teste[a] = buffer[a];
        
        printf("%d: %d\n", a, teste[a]);
    }

    fclose (f);
    return 0;
}

It returns this:

0: 171051569
1: 171182643
2: 53
3: 0
4: 0

I've tried everything. What on earth is going on? I appreciate any help.

Upvotes: 0

Views: 93

Answers (1)

John Kugelman
John Kugelman

Reputation: 361595

The file is in the wrong format. It contains text, not binary, numbers. You can tell because 171051569 is the little endian encoding of "\x31\x0a\x32\x0a", or "1\n2\n" after converting the ASCII hex codes to characters.

If you want to open the file as "rb" and read it with fread then you need to save the numbers in binary format.

Alternatively, if you want to read it as is then open it as "r" and use text input routines such as fgets and sscanf.

Upvotes: 2

Related Questions