Quik19
Quik19

Reputation: 362

fread() - Want to read an integer but it is returning garbage

I have a dynamic .txt file called library.txt, which has only one line of data. It is exactly this one:

63Book Title1|Book Author 1|Book Editor 1|2014|English|255|99.989998|

I'm trying to read the first integer on the file (in this case, the number "63") using the void readInteger() function that I created:

void readInteger(){
FILE *arq = fopen("library.txt", "r+");
if(arq == NULL){
    printf("ERROR WHILE OPENING FILE!!!");
    return;
}

int x;
fread(&x, sizeof(int), 1, arq);
printf("%d", x);
return;
}  

But the function always keep printing the crazy number "1866609462".
Does anyone know what is wrong with my code? Can you guys help me please?

Upvotes: 1

Views: 217

Answers (1)

R Sahu
R Sahu

Reputation: 206557

fread is not the right function to use to read formatted data. Use fscanf instead.

fscanf(arq, "%d", &x);

Upvotes: 6

Related Questions