0
I’m studying file now, I just want me to be able to read a file line:
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);
}
What functions
feof
andfgetc
that you used make?– Woss
fgetc reads a character. Feof was used in while -> while not reaching the end of the file(EOF)
– VitorLP
And if instead of running until the end of the file you did until it found the character
\n
?– Woss
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?
– Maniero
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
– Victor Eyer
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.
– VitorLP
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.
– anonimo
To use these functions I would have to limit, because they use maximum size, as I would limit?
– VitorLP
What is the maximum possible length of a line? 1000, 3000, 10000 characters?
– anonimo
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.
– Maniero
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);
– Isac