How to read only one line of the C file?

Asked

Viewed 80 times

0

I’m studying file now, I just want me to be able to read a file line:

inserir a descrição da imagem aqui

I made this code, but it reads everything. I’ve tried using fscanf, fgetc, fgets, "n"; but I couldn’t find a solution. Can you help me? I wanted the simplest way possible.


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

main(){
    FILE *p;
    if((p=fopen("votos.txt","r"))== NULL){
        printf("\n Nao foi possivel abrir o arquivo");
        exit(0);
    }
    char c;
    while(!feof(p))
    {
        c = fgetc(p);
        printf("%c", c);
    }
    fclose(p);
}


  • 2

    What functions feof and fgetc that you used make?

  • fgetc reads a character. Feof was used in while -> while not reaching the end of the file(EOF)

  • And if instead of running until the end of the file you did until it found the character \n?

  • 2

    Is it known that each row always has 3 digits? What is the maximum size that the file can have? It has some restriction of what it can do?

  • Specifies more what you want to do. A simple fscanf already reads only one line and positions the pointer in the right place for the next read

  • I already tried to use n and the scanf, I could not. Maniero, the file is just that, I just wanted to show on the screen only one line of these.

  • If you want to store the entire line before displaying it then you will have to reserve space for all its characters. To read the whole line the gets function, or better still the fgets, is more suitable. Explain better what you want to do.

  • To use these functions I would have to limit, because they use maximum size, as I would limit?

  • What is the maximum possible length of a line? 1000, 3000, 10000 characters?

  • You said the file is this so you know the size of the line and the file, so the best solution is to read the whole file at once and play in the buffer and then pick up each line because you know it has size 4 (can be 5 depending on the format of the line break)there’s no need to complicate or slow down the way you want to and they’re suggesting you.

  • If you only have one number on each line of the file, you can read them easily with fscanf(arquivo, " %d", &variavel_para_o_numero_lido);

Show 6 more comments

1 answer

0

In your case, I think the easiest solution would be:

int main(){
    FILE *p;
    if((p=fopen("votos.txt","r"))== NULL){
        printf("\n Nao foi possivel abrir o arquivo");
        exit(0);
    }

    int val;
    fscanf(p, "%d", &val);
    printf("%d", val);

    fclose(p);
}

Read the first interim and put it in the variable val. On the next call, fscanf read the second value, and so on.

Browser other questions tagged

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