【发布时间】:2020-03-22 21:37:27
【问题描述】:
#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;
}
我期待这样的输出:
文本:伪文本
编辑? (是/否):是的
输入文本:再次虚拟文本
按回车后程序应该退出。
但我得到这样的输出:
文本:伪文本
编辑? (是/否):是的
程序退出而不接受输入。
在 wsl(Debian 10) 和 gcc (Debian 8.3.0-6) 8.3.0 上编译
并尝试在 "%c "[ scanf("%c ",&Conformation_Flag); ] 但是输入后它没有关闭
代码中的内容
【问题讨论】:
-
请不要混用输入法。
scanf("%c",&Conformation_Flag);在输入缓冲区中留下一个换行符,第一个fgets将其作为空行拾取。另外,最好使用面向流的文件打开功能fopen。 -
您需要在第一个
read之后为str1添加一个空终止符。你不应该使用printf("%s")来打印一个可能没有正确地以空值终止的缓冲区。
标签: c data-structures