A function that reads only the last integer number written in a text file and returns?

Asked

Viewed 30 times

-2

 FILE * save;

int funcao () {

int d;

char linha[100];

save = fopen ("light.txt" , "r");

if (save == NULL) {

    printf("Erro ao abrir o arquivo\n");

    return -1;

}

else {

    while (!feof){

         fgets(linha, 99, save);

    }

}

sscanf(linha, "%d", &d);

printf("\n%d\n", d);

return d;

}
  • Is it a text or binary type file? Is the number of lines predetermined or not? Is the size of each line fixed or variable? Are there multiple numbers in each row? It may vary from row to row?

  • Hello. It is a text file, the number of lines increases daily and each line has variable size. There will only be an integer number on each line [1, 30]. I need the function to read which is the last number on the last line and return it.

  • Do you know what reasoning you would follow and only have problems with the use of i/o functions? Or your doubt is in fact the reasoning of the problem, not the functions themselves of the library?

  • I’m a beginner yet. I don’t know many functions to manipulate files and don’t know which ones could help me do what I want. I think both reasoning and functions.

  • After all, did the above code work or not? If it did not work, what was the result obtained and what was expected? Note that the reference to fseek.

  • The description code didn’t work, nor did the anonymous response. Apparently the vector line does not read the end of the last line in which it has the number and fscanf ta reading something I do not know where it comes from.

Show 1 more comment

1 answer

0

Make sure it’s something like:

#include <stdio.h>
int main() {
    FILE * save;
    char linha[100];
    int d;
    save = fopen ("light.txt" , "r");
    if (save == NULL) {
        printf("Erro ao abrir o arquivo\n");
        return -1;
    }
    else {
        while (fgets(linha, 100, save) != EOF )
            ;
        fclose(save);
    }
    sscanf(linha, "%d", &d);
    printf("\n%d\n", d);
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.