I am trying to read from a file in C using fgets()
however I have run into the following problem:
Although I can open the file successfully using fopen()
:
if ( file=fopen(filename, "r") == NULL )
{
printf("Couldn't open specified file. Please try again.");
exit(1);
}
I can't read anything from it. I am using the following loop, although nothing is printed and the execution terminates successfully.
while ( (fgets(inputLine, 1023, file)) != NULL)
{
printf("Hello world");
}
This is independent of the actual filename, filesize or file contents. Nothing seems to work and nothing is shown up as an error in the debugger. A sample file I have tried is the following directly copied and pasted:
test.txt
#include <stdio.h>
int main ()
{
printf("Hello World");
}
Do you have any guess as to why this is happening?
NOTE: I have taken the loop code from this S'O question so I guess it's right.
This is incorrect:
if ( file=fopen(filename, "r") == NULL )
Try:
if ( (file=fopen(filename, "r")) == NULL )
They way you have written it is equivalent to file = 0
(assuming the file is succesfully opened. If not, it is the same as file = 1
). This is not what you want.