Home > database >  fscanf keeps returns wrong value for integers
fscanf keeps returns wrong value for integers

Time:04-20

I'm trying to access a file called 'movies.dat' that contains a movies title, gross revenue, and year of release.

Currently my program will retrieve the title and year correctly. However, the gross revenue will return the wrong value only when I try to retrieve it as an int. It will also return it correctly if the value is less than 2150000000 I tried retrieving it as an long but that returns the same issue.

movies.dat

Gone_with_the_Wind 3713000000 1939
Avatar 3263000000 2009
Titanic 3087000000 1997
Star_Wars 3049000000 1977
Avengers:_Endgame 2798000000 2019
The_Sound_of_Music 2554000000 1965
E.T._the_Extra-Terrestrial 2493000000 1982
The_Ten_Commandments 2361000000 1956
Doctor_Zhivago 2238000000 1965
Star_Wars:_The_Force_Awakens 2206000000 2015
Snow_White 2150000000 1937
Jurassic_Park 2100000000 1993
Jaws 2100000000 1975
Avengers:_Infinity_War 2050000000 2018
The_Exorcist 2000000000 1973

Output

Gone_with_the_Wind -581967296 1939
Avatar -1031967296 2009
Titanic -1207967296 1997
Star_Wars -1245967296 1977
Avengers:_Endgame -1496967296 2019
The_Sound_of_Music -1740967296 1965
E.T._the_Extra-Terrestrial -1801967296 1982
The_Ten_Commandments -1933967296 1956
Doctor_Zhivago -2056967296 1965
Star_Wars:_The_Force_Awakens -2088967296 2015
Snow_White -2144967296 1937
Jurassic_Park 2100000000 1993
Jaws 2100000000 1975
Avengers:_Infinity_War 2050000000 2018
The_Exorcist 2000000000 1973

Code

#include<stdio.h>
#include<assert.h>

int main(void)
{
    //Open File and check it opened correctly
    FILE * fp;
    fp = fopen("movies.dat", "r");
    assert("Error: Could not open file" && (fp != NULL));

    char text[256] = "\000";
    int gross = 0;
    int year = 0;

    //loop
    while(!feof(fp))
    {
        //basic attempt
        fscanf(fp, "%s %d %d", text, &gross, &year);
        printf("%s %d %d\n", text, gross, year);
    }

    //Close File
    fclose(fp);
}

CodePudding user response:

2150000000 is almost 231−1, which is the value of INT_MAX when int is 32 bits. Try to read the big numbers in a long long.

  •  Tags:  
  • c
  • Related