unusual behaviour with printf with infinite while loop - c

When I run the below program, I do not get any output.
#include <stdio.h>
int main()
{
printf("hello");
while(1)
{
}
return 0;
}
whereas if i edit the printf command to add a '\n' character to the end of the string, then the expected output comes. what is going on in the first code? I simply cannot understand it.

This is because stdout is line buffered, i.e. the output is not written to the device (the terminal) until a full line has been collected.
You can call fflush(stdout); to force a flush of the buffer to the terminal. Do not try to flushing stdin by the way, that's not allowed.

try
printf("hello\n");
or
printf("hello");
fflush(stdout)

Use printf("hello\n");
For more info see answers to this question.

Related

Printf and sleep inside for loop? [duplicate]

This question already has answers here:
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 6 years ago.
I can't understand why following code works like this..I mean: instead of printing "hello" after each one second delay...it wait 5 second and display hellohellohellohellohello at once.
#include <stdio.h>
int i;
for(i=0; i<5; i++) {
printf("hello");
sleep(1);
}
The output of printf() (stdout) is line buffered by default if the output is going to a tty. You need one of
printf("hello\n");
or
printf("hello");
fflush(stdout);
The latter will explicitly flush the output each iteration.
printf do not print immediatly, instead it cache it line per line.
Add "\n" (newline) add the end of your string printf("hello\n"); or use write function instead write(STDOUT_FILENO, "hello", sizeof("hello"));.
You are writing to standard output (stdout), which is buffered. If you want the content to be immediately printed, you may flush the output or insert a newline.
You can add a \n to the end of your string so as to print the newline -- change your printf line to:
printf("hello\n");
For flushing the stdout buffer call fflush on it, after the printf:
#include <stdio.h>
int main() {
int i;
for(i=0; i<5; i++) {
printf("hello");
fflush(stdout);
sleep(1);
}
}
In general the output can be buffered. That means the implementation collects several bytes before actually writing to the console. You can explicitly write the buffer by fflush(stdout). This is true for all file descriptors, one of which is stdout, the terminal output. You can disable the buffering with setbuff(stdout, NULL), but this is almost never a good idea performance wise.
Try this:
int i;
for(i=0;i<5;i++){
printf("hello\n");
i=0;
sleep(1);
}

Unable to understand behaviour of "system" function call in C program

When I run the following program, the output of system("ls -l") is displayed before that of printf. Why does it happen?
#include<stdio.h>
int main()
{
printf("\nHello world");
system("ls -l"); // output of this statement is displayed before that of the preceding
// printf statement
return 0;
}
Thanks.
printf is buffered. AFAIK the buffer is written to the output only when a there is a \n or when you explicitly flush it (via fflush(3)).
So what happens is, printf writes the \n to the output, then buffers the rest of your string. Then ls -l is executed and when your program finishes the buffer is flushed automatically.

printf sleep \n

I was trying something when I saw this strange behavior. Can someone please explain it to me.
#include<stdio.h>
int main()
{
printf("utkarsh");
sleep(10);
printf("dixit");
}
The expected output is print "utkarsh" then wait for 10 seconds, print "dixit" next to it.
But what I observed was that it waits for 10 seconds and the prints "utkarshdixit".
If I add a \n at end of utkarsh, it works as expected.
printf("utkarsh\n");
Could someone help me understand why am I seeing such behavior ?
you're encoutering buffering.
try to do
fflush(stdout);
in front of the sleep
printf is buffering until you decide to write a '\n'.
You can use : flush to force to print
Here, try this
#include<stdio.h>
int main()
{
printf("utkarsh");
fflush(stdout);
sleep(10);
printf("dixit");
}
There's buffering of the standard out going on. you have to explicitly flush it.
There is buffering in stdout stream. Hence you need to flush once before sleep.
But when you used a '\n', the c run-time automatically flushes the stdout buffer for you. Hence you see this behaviour

Why does printf not work before infinite loop?

I am trying to make a small program that includes an infinite loop to wait for signal input from the user. I wanted to print out a message about the current working directory before beginning the infinite loop. The message works on its own, but when I put the infinite loop into the code the message does not print out (but the terminal does loop infinitely). The code is:
#include <stdio.h>
int MAX_PATH_LENGTH = 100;
main () {
char path[MAX_PATH_LENGTH];
getcwd(path, MAX_PATH_LENGTH);
printf("%s> ", path);
while(1) { }
}
If I take out while(1) { } I get the output:
ad#ubuntu:~/Documents$ ./a.out
/home/ad/Documents>
Why is this? Thank you!
When you call printf, the output doesn't get printed immediately; instead, it goes into a buffer somewhere behind the scenes. In order to actually get it to show up on the screen, you have to call fflush or something equivalent to flush the stream. This is done automatically for you whenever you print a newline character* and when the program terminates; it's that second case that causes the string to show up when you remove the infinite loop. But with the loop there, the program never ends, so the output never gets flushed to the screen, and you don't see anything.
*As I just discovered from reading the question itsmatt linked in a comment, the flush-on-newline only happens when the program is printing to a terminal, and not necessarily when it's printing to a file.
Because you don't have a new-line character at the end of your string. stdout is line-buffered by default, which means it won't flush to console until it encounters a new-line character ('\n'), or until you explicitly flush it with fflush().
Perhaps the output is not getting flushed. Try:
printf("%s> ", path);
fflush(stdout);
Because the stdout hasn't been flushed.
Call
fflush(stdout);
before your loop.
Because the output is not flushed.
Add
fflush(stdout);
before the while loop will solve the problem.

Why does printf() not print anything before sleep()?

I'm just learning C with Kernighan and Ritchie's book; I'm in the basics of the fourth chapter ("Functions and Program Structure"). The other day I became curious about the sleep() function, so tried to use it like this:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf(" I like cows.");
sleep(5);
return 0;
}
The problem is the output of the program, it looks like it does the sleep() first and then the printf(), in other words, it waits five seconds and then prints the string. So I thought, maybe the program gets to sleep() so fast that it doesn't let printf() have his work done like I want, that is print the string and then sleep.
How can I show the string and then put the program to sleep?
The compiler is GCC 3.3.5 (propolice) in OpenBSD 4.3.
printf() writes to stdout (the default output stream) which is usually line buffered. The buffer isn't flushed by the time sleep is called so nothing is displayed, when the program exits all streams are automatically flushed which is why it prints right before exiting. Printing a newline will usually cause the stream to be flushed, alternatively you could use the fflush function:
int main(void)
{
printf(" I like cows.\n");
sleep(5);
return 0;
}
or:
int main(void)
{
printf(" I like cows.");
fflush(stdout);
sleep(5);
return 0;
}
If you are printing to a stream that is not line buffered, as may be the case if stdout is redirected or you are writing to a file, simply printing a newline probably won't work. In such cases you should use fflush if you want the data written immediately.
Your problem is that printf (and anything else that uses the stdio library to write to stdout (standard output)) is buffered - line buffered if it goes to the console, and size buffered if it goes to a file. If you do a fflush(stdout); after the printf, it will do what you want. You could try just adding a newline ('\n') to your string, and that would do the right thing as long as you don't redirect standard output to a file.
I'm not 100% sure, but I think stderr isn't buffered, which can cause confusion because you might see output you made to stderr before output you previously made to stdout.
Buffering means that all the output is stored in a place (called buffer) and is output after a certain amount of data is present in it. This is done for efficiency reasons.
Some (most?) implementations clear the buffer after a newline when writing to the console, so you can also try
printf(" I like cows.\n");
instead of the call to fflush()
I implemented time encounter as following;
for (int i = 1; i <= 60; i++) {
printf("%02d", i);
fflush(stdout);
sleep(1);
printf("\b\b");
}

Resources