Search code examples
cfgets

Getting trash reading files with fgets


I have a file (MyFile.txt) with N rows, wich one has 7 fields:

(id_artist: int, artist: char, id_song: int, song: char, duration: int, year: int, valoration: int)

They are all separated by a space (' '). I need a function that, given an id of a song (int), returns the duration of the song with the same id.

Here is my code:

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

int main()
{
    int ID;

    FILE *fp = fopen("MyFile.txt","w");
    fprintf(fp,"100 Lennon 1100 Imagine 181 1977 1\n123 Queen 1122 KQueen 190 1983 2\n144 Nirvana 1144 Polly 175 1989 3\n");
    fclose(fp);


    printf("Ingrese id: ");
    scanf("%d",&ID);

    int res = duracion(ID);
    printf(res);

    return 0;
}

int duracion(int id){


    char line[100], artista[30], nombre[30];
    int id_art, id_song, dur, ano, valoracion;

    FILE *file = fopen("MyFile.txt","r");

    while( fgets(line,100,file) != NULL)
    {
        //printf(line);

        sscanf(line,"%d %s %d %s %d %d %d", &id_art, artista, &id_song, nombre, &dur, &ano, &valoracion);

        if(id == id_song){
            return dur;
        }

    }

    return 0;
}

The function actually finds the indicated row if it exists, but the function never returns 0 or 1. If I uncomment the commented line and search for a non-existintg id, I get an output like this:

100 Lennon 1100 Imagine 181 1977 
d123 Queen 1122 KQueen 190 1983 2
<144 Nirvana 1144 Polly 175 1989 3
é

I debugged the code trying to find where the problem is but I don't get it.


Solution

  • printf(res);          //needed specifier %d 
    

    You forgot format specfier in printf here.

    Note- Also you forgot to close file after opening it in your function.