Search code examples
cstringwhile-loopfifofgetc

While loop not working with fgetc


So here's what is am trying to do:

  1. I am asking the user to input a number of sentences

  2. Whenever he wants to stop he will press Q (captial letter)

  3. And then the next processing should start.

What i am getting right now:

  1. The user is prompted to enter as many sentences as he wants
  2. But when he presses Q the control doesn't shift from the while loop to the next instruction.

It is a FIFO program.If you see any other errors do report them.Thanks!

Here's the Code:

#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
void main()
{

int i=0,fd;
char str[500]="",ch;

char *myfifo="/home/rahulp/Desktop/myfifo";

mkfifo(myfifo,0666);    

printf("Enter the sentences:");

while((ch=fgetc(stdin))!='Q')
{
    printf("ch===%c",ch);
    str[i++]=ch;

}
str[i]='\0';

fd=open(myfifo,O_WRONLY);

if(fd<0)
{
    printf("Cannot open fifo");
}
else
{
    write(fd,str,strlen(str));
}

close(fd);
unlink(myfifo); 
}

Solution

  • Ignoring the possibility that something with mkfifo is going on, this is how you should read stdin:

    int ch;
    
    printf("Enter the sentences:");
    fflush(stdout);
    
    while ((ch = fgetc(stdin)) != EOF)
    {
        if (ch == 'Q')
            break;
        printf("ch=%c\n", ch);
        str[i++]=ch;
    }
    str[i]='\0';