Hi all, I am using openwrt with musl toolchain. Here I am facing some strange behavior wrt to fprintf and fscanf.
For the following example c program
#include <stdio.h>
#include <string.h>
int
prompt_yesNo(char *promptStr)
{
char inbuf[8] = {0};
int ret = 0;
fprintf(stdout, "%s\b", promptStr);
while(fgets(inbuf, sizeof(inbuf), stdin)) {
if (!strchr(inbuf, '\n'))
while(fgetc(stdin)!='\n');
if ((0 == strcasecmp(inbuf, "y\n")) || (0 == strcasecmp(inbuf, "yes\n"))) {
ret = 1;
goto out;
} else if ((0 == strcasecmp(inbuf, "n\n")) || (0 == strcasecmp(inbuf, "no\n"))) {
ret = 0;
goto out;
}
printf("Invalid input. Please enter the choice(y/n) again :");
}
out :
return ret;
}
int main()
{
int a;
char bufPrompt[128] = {0};
sprintf(bufPrompt, "Do you want to enter a size (y/n) : ");
if (prompt_yesNo(bufPrompt))
{
fprintf(stdout, "Please enter the size : ");
fscanf(stdin, "%u", &a);
fprintf(stdout,"entired size is %d",a);
}
return 0;
}
The expected output should be
Do you want to enter a size (y/n): y [given by me]
Please enter the size: 8 [given by me]
entired size is 8
But for me when I give input as y, console is hanging and not printing "Please enter the size" it is expecting for a input i.e when we provide input 8 it is completing the rest of code and shows me output entered size is 8.
In online there have been few solutions like use setvbuf(stdout, NULL, _IONBF, 0); in every main function or use fflush(stdout) after printf/fprintf of all packages to overcome issues like this, but this won't be an appropriate way. Can we modify definition of printf or something in toolchain level to overcome this issue?
Or are there any other solutions for the same?