0
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdlib.h>
int main()
{
    int fd1;
    char  * myfifo = "/home/karthik/code/test.txt";
    mkfifo(myfifo, 0666);
    char str1[80],str2[80],Conformation_Flag;

    //Shows what's in file.
    fd1 = open(myfifo,O_RDONLY);
    read(fd1,str1,80);
    printf("Text : %s",str1);
    close(fd1);
    printf("Edit? (y/n) : ");
    scanf("%c",&Conformation_Flag);
    
    if(Conformation_Flag == 'y')
    {   
        printf("Enter the text : ");
        fflush(stdin);
        //Take input and write to file.
        fd1 = open(myfifo,O_WRONLY);
        
        fgets(str2,80,stdin);
        
        write(fd1,str2 ,strlen(str2)+1);
        
        close(fd1);
    }
    else if(Conformation_Flag == 'n')
    {
        exit(0);
    }
    else
    {
        printf("Invalid Option!");
    }
             

return 0;
}

I'm expecting output like this :

Text : Dummpy text

Edit? (y/n) : y

Enter the Text : Again Dummy text

After Pressing enter Program should be exit.

But i'm getting output like this :

Text : Dummpy text

Edit? (y/n) : y

program exiting without taking input.

Compiling on wsl(Debian 10) and gcc (Debian 8.3.0-6) 8.3.0

And tried giving space at "%c "[ scanf("%c ",&Conformation_Flag); ] But it's not closing after taking input

What is worng in the code

Community
  • 1
  • 1
  • 2
    https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf – Mat Mar 22 '20 at 12:03
  • 1
    Please do not mix input methods. `scanf("%c",&Conformation_Flag);` leaves a newline in the input buffer which is picked up as an empty line by the first `fgets`. Also, it is better to use the stream-oriented file opening function `fopen`. – Weather Vane Mar 22 '20 at 12:03
  • https://stackoverflow.com/questions/2979209/using-fflushstdin?noredirect=1&lq=1 – Mat Mar 22 '20 at 12:03
  • 2
    You need to add a null terminator to `str1` after the first `read`. You ought not use `printf("%s")` to print a buffer that may not be properly null terminated. – William Pursell Mar 22 '20 at 12:18

1 Answers1

0

As the first comment suggests, new line is left in the stdin and gets read in the next stdin reading op.

As a hackish solution, use the following:

    //scanf("%c",&Conformation_Flag);
    Conformation_Flag = fgetc(stdin); //reads the y or n
    fgetc(stdin); // reads a new line

here is a variant with getline() as a replacement. E.g. based on How to read string from keyboard using C?

    char *line = NULL;  /* forces getline to allocate with malloc */
    size_t len = 0;     /* ignored when line = NULL */
    int read_n = 0;

    read_n = getline(&line, &len, stdin);
    Conformation_Flag = line[0];
    free(line);
Artem Trunov
  • 1,340
  • 9
  • 16