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;
}
C-reading multiple lines
Started by geeko, Oct 19 2008 10:42 AM
1 reply to this topic
#1
Posted 19 October 2008 - 10:42 AM
|
|
|
#2
Posted 19 October 2008 - 11:23 AM
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


Sign In
Create Account


Back to top









