How can I read a txt file in C, line by line?

Asked

Viewed 198 times

0

I’m a beginner in C, I’m trying to read a txt file that has more than one line, but when I use fgets it only reads the first line, as I can read the entire file?

what I’ve done so far

    void main()
{
  FILE *arq, *arq1;
  char Linha[50];
  char *result;
  int i;
  char string[50];

    //printf("digite uma das opcoes\n");
    //printf("(1) Converter texto para maiusculo\n");
   // printf("(2) Converter texto para minusculo\n");
   // printf("(3) Primeira letra em maiusculo\n");
    //printf("(4) inverter texto\n");





  arq = fopen("string.txt", "rt");
  if (arq == NULL)  // Se houve erro na abertura
  {
     printf("Problemas na abertura do arquivo\n");
     return;
  }
  i = 1;
  while (!feof(arq))
  {

      result = fgets(Linha, 50, arq);
      if (result)
     printf("Linha %d : %s\n",i,Linha);
      i++;
  }
    //Linha[0]= toupper(Linha[0]);
    //printf("%s",Linha);
    i=0;
    for (i=0; i<50;i++)
    {
      string[i]= toupper(Linha[i]);


    }

printf("%s",string);
fclose(arq);

return 0;

}

1 answer

1

Hello. You are on the right track when using fgets. If you read the documentation of this function you will see that it returns null when it reaches the EOF or no characters are read. And what you want to do is read line by line until you get to the EOF. So just make a loop like:

 while(fgets(Linha, 50, arq)) {
      printf("Linha %d : %s\n",i,Linha);
      i++; 
} 
//Enquanto o fgets não retornar null faz o que quiser com a linha lida para a variavel linha
  • I got it, thank you very much.

Browser other questions tagged

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