Theocharis K.
Theocharis K.

Reputation: 1341

Strange issue while trying to read from a file with fgets()

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.

Upvotes: 0

Views: 593

Answers (2)

md5
md5

Reputation: 23727

Apart from the fact you are doing a mistake in the condition of fopen, there is also a potential problem with snippets such as:

while ( (fgets(inputLine, 1023, file)) != NULL)
{
    printf("Hello world");
}

By default, the standard output stream stdout is line-buffered. This means that you should add a \n or a call to fflush to force the data to being effictively written.

fflush(stdout);

Upvotes: 0

William Pursell
William Pursell

Reputation: 212574

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.

Upvotes: 6

Related Questions