user3169322
user3169322

Reputation: 9

fgets() goes into infinite loop reading from stdin

I wrote the following code, but it gets stuck into an infinite loop. Can somebody help me out at this topic?

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

void main()
{
    FILE *fp;
    char s[10];


    fp=fopen("text1.txt", "w");

    if(fp==NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    while(fgets(s, sizeof(s), stdin)!=NULL)//Reads until the NULL character.
        fputs(s, fp);//Write to the file pointed by fp..


    fclose(fp);
    getch();
}

Upvotes: 1

Views: 2716

Answers (2)

rjv
rjv

Reputation: 6776

If you are typing in the input use ctrl+z to terminate the input.I tried the code on linux and it works fine.ctrl+z represents EOF on windows.

If you are not typing in input and using redirection,the code works fine as such.

Upvotes: 2

unwind
unwind

Reputation: 400069

This program will run, as expected, until the input signals "end of file".

If you're not using input redirection (e.g. running it as myprogram < somefile.txt) but instead running with the console (keyboard) as the input device, you must manually signal end of file to cause the loop to end.

In Linux, this is done by pressing Ctrl+D, in Windows it's Ctrl+Z.

Upvotes: 2

Related Questions