Behaviour of stdout and printf [duplicate] - c

This question already has an answer here:
C's printf and fprintf(stdout,) are not printing
(1 answer)
Closed 6 years ago.
Just see the below program,
#include <stdio.h>
int main()
{
printf("hai");
while(1);
}
The above code is not printing hai and its just waitinG. But if I add
printf("hai\n");
its working.
Can I know what happening internally?

Writing printf("hai\n"); instead will cause, due to the newline character, the output buffer to be flushed, so you'll see the output before entering the infinite loop. There are other ways of flushing the output buffer, but appending the newline character is particularly simple.
Technically the behaviour of a tight loop like while(1); is undefined in C, but that is unlikely to be the cause of your problem.

printf("hai"); won't show something immediateley, you need to flush stdout's buffer with either printf("\n"); or fflush(stdout);

Your standart output stream (stdout) is buffered, so it will only flush (and display what is in it) when it is either manually forced or when it recieves a newline character ('\n').
You can change this behavior with the library function setbuf()
You can also manually flush the buffer (force it to immideatly display whats currently in it) by using fflush(stdout);

Related

How to use ffllush(stdout) in c? [duplicate]

This question already has an answer here:
Flushing buffers in C
(1 answer)
Closed 1 year ago.
I know about fflush(stdin) that it is undefined behavior according to standard. But when it comes to stdout, there is no such restriction. I did google to get the concept of using stdout as a parameter of fflush, but I couldn't get it.
Can someone elaborate the fflush function having stdout as a parameter with an easy example?
When printing (e.g. printf), the output is put into a buffer and may not be written to the console until a newline character is displayed. To ensure that everything in the buffer is written to the console, fflush(stdout) may be used.
One example is displaying the progress of some process:
for(int i = 0; i < 100; i++)
{
<...calculation...>
printf("."); // Print a dot after each iteration to show progress
fflush(stdout); // The dot may be buffered. This ensures that it is displayed immediately
}

I get all the lines inside the printf line in the end of the output [duplicate]

I am aware that most terminals are by default in line buffer mode. i.e. output is buffered and not directed to stdout until a new-line character is encountered.
So I would expect this to print nothing (at least before the buffer is filled up):
int main() {
while(1) {
printf("Haha");
sleep(1);
}
return 0;
}
It indeed prints nothing for a short period of time.
If I want to print "Haha" every second, I can either printf("Haha\n") or do fflush(stdout) after printf. (I know this is not so portable, but it's a solution nonetheless)
Now I recall the very classic scanf program (with my addition to while(1) loop to prevent buffer flushing on program exit):
int main() {
char char_in;
while(1) {
printf("Haha. Input sth here: ");
scanf("%c", &char_in);
}
return 0;
}
Now the program prints Haha. Input sth here: (and wait for my input). It is not here if I remove the scanf statement. Why is that so?
Thanks.
Now the program prints Haha. Input sth here: (and wait for my input). It is not here if I remove the scanf statement. Why is that so?
Because the standard (N1570 .. "almost C11") says so, ยง5.1.2.3/6 (emphasis mine):
The least requirements on a conforming implementation are:
[..]
The input and output dynamics of interactive devices shall take place as specified in 7.21.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input.
[..]
Even though your output does not contain a newline and is send to a line buffered stdout, it has to appear before your program is allowed to wait for input. This is because stdout and stdin are connected to a terminal and thus are (Attention: This is implementation defined!) what the standard calls "interactive devices".

Why does getchar wait after one character is entered? [duplicate]

This question already has answers here:
How to avoid pressing Enter with getchar() for reading a single character only?
(14 answers)
Closed 4 years ago.
Here is my code:
#include <stdio.h>
int main()
{
char a = getchar();
printf("char: %c", a);
}
I'm compiling this with gcc.
When running, the program waits for input even after one character is entered on console. Shouldn't it immediately exit and print the character? I'm running this on Ubuntu for Windows, if that can make any difference.
stdin is your default input stream. The default buffering mode of stdin is line buffered. So it waits for the \n to be entered. Then only there is something to read from the input stream and then getchar gets the input and works with it.
The operating system often buffers console input until a new line is entered, such that your program will not even receive the single character before. Probably nothing you can do about that.

Code before while(1) does not run [duplicate]

This question already has answers here:
printf not printing to screen
(3 answers)
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 7 years ago.
I have code like this below:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("hello");
while(1){
// whatever here
}
}
and the question is: why the first instruction is skipped? It runs only the loop, hello is never printed. I compiled it with gcc and g++ with the same result.
It does run, it's just that the output buffer is not flushed before your while.
Use printf("hello\n"); instead. The newline character will flush the buffer so writing the output immediately to your console.
Your assumption is wrong, your code does run, only stdout is not flushed, but buffered.
Use fflush(stdout) after printf("hello"), this forces stdout to be printed.
And, as #Bathsheba pointed out, also a newline character ("\n") within the printf forces it to flush, which is explained in this SO question.

Printf() before line causing segmentation fault does not execute [duplicate]

This question already has answers here:
Execution of printf() and Segmentation Fault
(4 answers)
Closed 1 year ago.
When a segmentation fault occurs, the printf() before it does not execute.
main()
{
printf( "something" );
statement; //this statement causes a segmentation fault
}
In the situation above, why does the printf() not execute?
So do I need to use valgrind in such a case(which prints all printf() before the faulty statement).
Make sure you include a newline "\n" in your printf statement. Normally, at least in UNIX systems, stdout is line-buffered so newline character makes the line to appear immediately. You probably omitted "\n" (or your output is not flushed for other reason) and that's why you can't see the printed string.
Another option is to flush the output yourself using fflush(stdout) after calling printf.
An output stream can fail to be output before a program crash but you can force the bytes to be output by flushing them with fflush().
I usually do it with something like this:
if (trace) { fflush(stdout); }
Output via printf() and any other standard I/O function is buffered in the standard C library.
You need to call fflush() to ensure the output is sent to the tty before your program crashes.

Resources