Going back to normal terminal I/O after closing ncurses window - c

In a game I made I create an ncurses window using initscr(), then the user plays the game and when the game ends the program closes the window using endwin() and then prints some statements and gets input from the user using printf and scanf, respectively. My problem is that whenever the game ends scanf always executes before printf. So it waits for a response, and once the user enters the response it prints everything that was before and after the scanf statement. Here is some example code:
...
endwin();
system("clear"); /* Clears terminal window */
printf("New high score!\nPlease enter your first name: ");
scanf("%s",name);
... /* file I/O stuff */
printf("Congratulations, %s!",name);
As you can see, the printf statement is before the scanf statement but for some reason scanf executes first. I tested the code without an ncurses window and I get the desired result. Does anyone know what is causing this?

Nothing to do with curses.
This statement is obviously wrong since using curses makes a difference, as the question states:
As you can see, the printf statement is before the scanf statement but
for some reason scanf executes first. I tested the code without an
ncurses window and I get the desired result. Does anyone know what is
causing this?
While it is right that fflush(stdout) gives the desired result, that does not answer the question.
What is causing this is presumably the implementation-defined standard I/O characteristic to flush a line buffered stdout when input is requested (sometimes documented in man setbuf), and curses setting stdout to fully buffered, thereby disabling the automatic flush.

You can read about it in the manual page where it discusses NCURSES_NO_SETBUF:
to get good performance, most curses implementations change the output buffering from line-oriented to buffer-oriented (so that the library can make larger, more efficient writes)
because that meant that all writes to the standard output would be buffered, it was a nuisance. ncurses provided an option (the environment variable) to override the buffering.
that changed in 2012, by eliminating the stdout buffering altogether to solve a problem with signal handling.
however, "eliminating" the buffering means that ncurses uses its own buffer. It'll flush that in endwin, but doesn't flush stdout when switching to/from curses mode.
a few applications required modification to flush stdout.
The 2012 change for ncurses was part of the ncurses6 release in August 2015. The OP's question is in terms of ncurses5.9 (or earlier), since it describes an application where the standard output is buffered.

Related

Is it just best to flush stdout/stderr every single time?

From this stack overflow post: Is stdout line buffered, unbuffered or indeterminate by default?
From that post, it states that "The C99 standard does not specify if the three standard streams are unbuffered or line buffered: It is up to the implementation."
#include <stdio.h>
int main(void) {
printf("Enter name: ");
fflush(stdout);
printf("Another name: ");
fflush(stdout);
return 0;
}
So, does that mean every single time we print, and we want to make sure it is visible to the user, that it's the safest bet to just flush it every single time? Since buffering is up to the implementation?
#include <stdio.h>
int main(void) {
puts("Enter name:");
fflush(stdout);
puts("Another name: ");
fflush(stdout);
return 0;
}
Even on a newline, is it still best to just flush every single time?
I want to 100% make sure the user sees the output, therefore is it best to flush every single time? Even on stderr? Since buffering is up to the implementation?
Looking at the exact examples you show, it's unlikely there will be a visible difference from calling fflush. In particular, you just write two lines of data, and then exit. Normal exit from a program (either by calling exit or returning from main) requires:
Next, all open streams with unwritten buffered data are flushed, all open streams are closed, and all files created by the tmpfile function are removed.
So, the only possibility here would be if the system crashed (or something on that order) immediately after the first fflush call, but before your program exited.
I'd guess, however, that the real intent was when you print out the "Enter name: " prompt, you intended for the program to stop and read a name from the user:
printf("Enter name: ");
char name[256];
fgets(name, sizeof(name), stdin);
For cases like this, flushing the output stream is generally unnecessary.
In particular, the standard says:
When a stream is line buffered, characters are intended to be
transmitted to or from the host environment as a block when a new-line character is
encountered. Furthermore, characters are intended to be transmitted as a block to the host
environment when a buffer is filled, when input is requested on an unbuffered stream, or
when input is requested on a line buffered stream that requires the transmission of
characters from the host environment.
Now, you can make a little bit of an argument that this only talks about what's intended, not what's required. What that basically comes down to is fairly simple: the operating system could do some buffering over which your program has little or no control. So, what it basically comes down to is pretty simple: when you read from stdin, if anything has been written to stdout, but not flushed yet, it'll be flushed automatically before the system waits for input from stdin (unless you've done something like redirecting one or both to a file).
I'm reasonably certain that essentially every argument for doing that flushing explicitly is purely theoretical. In theory, there could be a system that doesn't do it automatically, and that might not quite violate any strict requirement of the standard.
In reality, however, actual systems fall into two categories: those on which the flushing is automatic, so you gain nothing by doing it explicitly, and those on which flushing simply won't do any good, so you gain nothing by doing it explicitly.
Just for an example of the latter, some old terminals for IBM mainframes worked in what you might call a screen-buffered mode. Basically, you'd send a form to the terminal. The user would then edit data into the form. Then when they had filled in the entire form, they pressed a "send" button, and all of the data for the whole form was sent to the CPU at once. On a system like this, calling fflush won't be (nearly) enough to make code work.
Summary
There are systems where calling fflush is unnecessary.
There are systems where calling fflush is insufficient.
I'm reasonably certain there is no system where calling fflush is both necessary and sufficient.
I want to 100% make sure the user sees the output, therefore is it best to flush every single time?
For "100% make sure" best practice is not based on flushing after output, but flushing stdout before input. This is especially true when the output does not end with a '\n'.
It is best to fflush(stdout); when
Right before input from stdin and ...
There has been some output since the prior input from stdin.
Calling fflush(stdout); more often than that does not impact functionality, but may unnecessarily slow code.
There is a 2nd case for fflush(stdout); even without input: Debugging. Sometimes a fatal error occurs with info buffered in stdout. So a fflush(stdout); is warranted prior to the suspected bad code for better analysis.
Even on a newline, is it still best to just flush every single time?
For "100% make sure", the rules for flushing stdout are soft enough to even oblige fflush(stdout); before reading in this case too.
Yet stdout should be unbuffered or line buffered on start-up (see next) and usually not require a flush in this case.
Even on stderr?
C spec has "As initially opened, the standard error stream is not fully
buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device."
As long as the write to stderr ends with a '\n' and buffering mode not changed, then the output should be seen.
Interesting to see how C++ handles end-of-line.
What is the difference between endl and \n in C++?
#paxdiablo nicely answers Why does printf not flush after the call unless a newline is in the format string?
Not really, no. I flush at logical chunks so I can tell more or less where the program crashed and don't have an extra hard debugging time because it crashed with output in the buffer.
The idea is I'm going to call fflush() just before going and doing something else besides produce more output.
Flush too much = slow code.
Calling fflush() right before reading input is harmless (the only question is whether it will do it implicitly or not), so if you're doing that for some reason there's no reason to stop doing it.

Need a function for delaying without clearing buffer in C language

I use Sleep() function under windows.h for delaying but it clears the buffer unlike sleep() under unistd.h.
Is there a function for delaying without clearing the buffer?
#include<stdio.h>
#include<windows.h>
int main(void)
{
printf("hello");
Sleep(2000);
return 0;
}
It appears that you are expected stdout to be line buffered, so that calling printf with no newline does not cause any actual output. However, the C language standard permits either line buffering or no buffering if stdout may be an interactive device. When using the Microsoft C runtime, stdout will be unbuffered.
Therefore, the string hello is being sent directly to standard output, bypassing the runtime library buffering altogether. The fact that you're calling Sleep() afterwards has nothing to do with it.
You can use setvbuf() to explicitly configure stdout for full buffering, so that the output will be sent only when you explicitly flush the stream. Note that the Microsoft C runtime does not support line buffering.
PS: you should also note that to the best of my knowledge there is no requirement for the runtime to provide a buffer of any particular size, or any rule preventing it from flushing the buffer for whatever reason might take its fancy. If your program must not write the output until a later time, I think the only completely safe way to do that is to buffer the data yourself.

Pause the execution of exe of a C code

I have developed a simple console utility in C which parses various text files.
IDE - Code Blocks
OS - windows
I intend to distribute its executable.
The executable works fine, however unlike when executed from the IDE, the execution does not pause/wait for keystroke at the end of execution.
I tried using getchar()/system("pause"), but the execution doesn't pause there.
Is there an alternative to wait for keystroke before ending execution, so that the user can view the output?
You can use
getchar();
twice , because its very likely that last '\n' newline character will get consumed by your getchar().
or use
scanf(" %c");
with that extra space
at the end of your file .
It depends on how other parts of your code receives input from the user (i.e. reading from stdin).
The getchar() approach will work fine if your program is not reading anything from the user, or is reading using getchar().
A general guideline, however, is to be consistent in style of input from every stream. Style of input refers to character-oriented (functions like getchar()), line-oriented (like fgets()), formatted (functions like scanf()), or unformatted (like fread()). Each one of those functions does different things depending on input - for example getchar() will read a newline as an integral value, fgets() will leave a newline on the end of the string read if the buffer is long enough, scanf() will often stop when it encounters a newline but leave the newline in the stream to be read next.
The net effect is that different styles of input will interact, and can produce strange effects (e.g. data being ignored, not waiting for input as you are seeing).
For example, if you are using scanf(), you should probably also use scanf() to make your program wait at the end. Not getchar() - because, in practice, there may well be a newline waiting to be read, so getchar() will return immediately, and your program will not pause before terminating.
There are exceptions to the above (e.g. depending on what format string is used, and what the user inputs). But as a rule of thumb: be consistent in the manner you are reading from stdin, and the user will have to work pretty hard to stop your program pausing before terminating.
An easier alternative, of course, is to run the program from the command line (e.g. the CMD.EXE command shell). Then the shell will take over when your program terminates, the program output will be visible to the user, so your program does not need to pause.
Don't use system("pause") since it's not portable. getchar should work on the other hand. Can you post some code? Maybe there's something on the keyboard buffer that's being consumed by your one and only getchar call.

Using STDIN and STDOUT subsequently

I'm writing a chat in C that can be used in terminal...
For receiving text messages, i have a thread that will print that message out on STDOUT
Another thread is reading from stdin...
The problem is, if a new message is printed to stdout while typing, it will be printed between what i typed.
I researched several hours an experimented with GNU readline to prevent this problem. I thougth the "Redisplay" function will help me here.. but I could not compile my program on Mac OSX if I used certain redisplay functions (it said ld: undefined symbols) whereas other functions worked properly... I compiled this program on an Ubuntu machine and there it worked... i really have no idea why...
Nevertheless, how can achieve that everything that is written to stdout will be above the text i'm currently writing?
You have basically two solutions.
The first is to use something that helps you dividing your screen in different pieces and as #Banthar said ncurses is the standard solution.
The second is to synchronize your writings and readings. The thread that is reading from the network and writing to the console may simply postpone the messages until you entered something from the keyboard, at that time you can simply flush your messages-buffer by writing all the messages at once. Caveat: this solution may cause your buffer to be overflow, you may either forget too old messages or flush the buffer when full.
If your requirement it to use only stdin and stdout (ie a dumb terminal), you will have to first configure you console input as not line buffered which is the default (stty -icanon on Unix like systems). Unfortunately I could not find a portable way to do that programatically, but you will find more on that in this other question on SO How to avoid press enter with any getchar().
Then, you will have to collate next outgoing message character by character. So when an input message is ready to be delivered in the middle of the writing of an output one, you jump on line, write the output message, (eventually jump one other line or do what is normally done for prompting) and rewrite be input buffer so the user has exactly the characters he allready typed.
You will have to use a kind of mutual exclusion to avoid that the input thread makes any access to the input buffer while the output thread does all that work.

Flushing buffers in C

Should fflush() not be used to flush a buffer even if it is an output stream?
What is it useful for? How do we flush a buffer in general?
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard ยง7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that.
See here for more on fflush() and fpurge()

Resources