I have a C program in which I am trying to get the user input as a whole line and writing to a memory mapped file to implement IPC. The weird thing is when I use fgets or StrinCchGetsA the program doesn't wait for input but jumps to the next instruction right away. This weird behaviour doesn't happen if I use scanf_s with format string "%s" but this stops inout with the first space. If I use the the format string "%[^\n]s" or %[^\n]" to account for spaces the weird behaviour happens again.
Here's my main function. It is simple the user presses 1 to read from the memory mapped file or 2 to write to it.
int main()
{
HANDLE hFMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1 << 16, L"Shared Memory");
if (!hFMap)
{
printf_s("Error: %u", GetLastError());
return 1;
}
else
{
void* p = MapViewOfFile(hFMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (!p)
{
printf_s("Error getting pointer\n");
return 1;
}
int ch = 0;
bool quit = false;
while (!quit)
{
printf(">>1 ");
scanf_s("%d", &ch);
switch (ch)
{
case 1:
readMem(p);
break;
case 2:
writeMem(p);
break;
case 0:
quit = true;
break;
}
}
}
return 0;
}
The problematic code of writeMem function is as follows
void writeMem(void* p)
{
char txt[128];
printf(">>2 ");
fgets(txt, _countof(txt), stdin);
strcpy_s((char*)p, _countof(txt), txt);
}
or
void writeMem(void* p)
{
char txt[128];
printf(">>2 ");
scanf_s("%[^\n]s", txt, _countof(txt));
strcpy_s((char*)p, _countof(txt), txt);
}
It displays >>2 >>1
in the command line which indicates that it didn't stop at fgets and it writes in the buffer and my variable ch
.
Why is that happening?