Jump to content

C-reading multiple lines

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
geeko

geeko

    Newbie

  • Members
  • PipPip
  • 27 posts
Hey guys i need your help again...I get to read a sentence from a text file but how to make it read multiple lines/sentences from a txt file.

Heres the code>>

#include <stdio.h>

int main()
{
FILE * pFile;
char mystring [100];

pFile = fopen ("questions.txt" , "r");
if (pFile == NULL) perror ("Error! File could not be Open!");
else {
fgets (mystring , 100 , pFile);
puts (mystring);
fclose (pFile);
}

printf("\n\n\n\n\n\n\n\n\npress any 'ENTER' to exit: ");
while(!getchar());

return 0;
}

#2
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
      while ( fgets (mystring , 100 , pFile) )
      {
         fputs (mystring, stdout);
      }
[edit]I usually have a skeleton something along this line.
#include <stdio.h>

int main()
{
   [COLOR="Blue"]static const char filename[] = "questions.txt";[/COLOR]
   FILE * pFile = fopen ([COLOR="Blue"]filename [/COLOR], "r");
   if ( pFile [COLOR="Blue"]!=[/COLOR] NULL )
   {
      char mystring [100];
      while ( fgets (mystring , [COLOR="Blue"]sizeof mystring [/COLOR], pFile) )
      {
         fputs (mystring, stdout);
      }
      fclose (pFile);
   }
   else
   {
      perror ([COLOR="Blue"]filename[/COLOR]);
   }
   return 0;
}
I put the success case closer to the test. Also, I find that the error message is more informative:

Quote

questions.txt: No such file or directory
Other stuff was keeping scope closer to use and making a two-step size issue a one-step one.