سؤال

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();
}
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top