Search code examples
ciofgets

C Programming: fgets() function is not reading the values that I think it should


I am trying to open and read a .txt file that simply contains a 2 digit number from 00 to 99.

Currently the file contains the following numbers: 05

When I read the first two values with fgets(), I instead get 48 and 53, and I've noticed whatever number I put in there, the number that fgets() grabs is 48 higher. While I could just subtract 48 from the number like I am doing now, I would like to figure out what I am doing wrong so that I don't have to do that. Here is the relevant section of my code:

char buff[3];
FILE *fp;
fp = fopen("savedata/save.txt","r");
fgets(buff, 3, fp);
SampleLevelIndex = (buff[0]-48)*10 + buff[1]-48;
fclose(fp);

Solution

  • Your file contain the characters '0' and '5'. Note that the ASCII code for '0' is 48.

    You are reading the values of the bytes, not the number represented. If you had an 'A' in the file, you would have the byte 65.

    Your approach works for manually converting numeric characters into a number (although you might one some extra checking, it will break if it doesn't contain two numbers). Or you could use a function like atoi() which converts a numeric string into the number.