Doubt about reading text files in C

Asked

Viewed 117 times

0

My problem is simple, I created a following file listing some movies:

Meu arquivo de listas

What I want is to literally read what is inside and print on the terminal, I am aware of the existence of functions of reading files(fscanf, fgets...) but they do not seem to suit my situation, because this function asks to pass a string per parameter, however I have no string in my code, so I understood reading the documentation of these functions, the string would be given by the user, however I do not have this string in my code, I want this string to be actually all my text contained already inside the file. `#include

include

int main (void) {

FILE *arquivo; 
char texto[760]; // variável "place holder" pra considerar o texto do bloco 
                      de notas
arquivo=fopen("lista.txt","r"); // abertura do arquivo pra leitura

if(arquivo==NULL) {
    printf("ERROR"); 
    exit(1); 
}


fgets(texto,  759, arquivo);  // fgets usado de forma totalmente errada, pois não sabia oq passar no lugar da string

fclose(arquivo); 

printf("%s", arquivo); `

Thank you in advance!

1 answer

0


As described in documentation, you need to pass a buffer to be used while reading:

Parameters

str

Pointer to an array of chars Where the string read is copied.

in a

Maximum number of characters to be copied into str (including the terminating null-Character).

stream

Pointer to a FILE Object that identifies an input stream. stdin can be used as argument to read from the standard input.

That said, use a buffer as follows:

char buffer[1024];
while(fgets(buffer, sizeof(buffer), arquivo) != NULL)
    printf("%s", buffer);
}
  • Thank you very much! really after doing what you said I managed to print right the list!

Browser other questions tagged

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