I was just getting familiar with sleep(), i found that
#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
printf("%d",i);
sleep(1);
}
return 0;
}
this does not print number per iteration rather dumps all numbers when gets out of loop....
but when i modify printf...
#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
printf("%d\n",i);
sleep(1);
}
return 0;
}
and now as i've added '\n' new line it works as expected... why it is behaving strangely in former one...
This is because the output buffer isn't being flushed (in other words, actually committed to the terminal). When you write a newline, the output buffer is more likely to be (but still not always, in some cases) flushed. Many terminal implementations do this to improve performance. To force the behaviour you want, you need to call fflush(stdout); after each printf call, like this:
#include<stdio.h>
int main()
{
int i=0;
printf("*********Testing Sleep***********\n");
for(i=0;i<10;i++)
{
printf("%d",i);
fflush(stdout);
sleep(1);
}
return 0;
}
What you are looking at is line buffered output. Actually writing to output is an expensive operation, so I/O streams are usually buffered. Actually writing the buffer is deferred until a specific event is encountered. In standard C, you have three types of buffering:
fully buffered - the buffer is written when full.
line buffered - the buffer is written when a newline is encountered (your case).
unbuffered - the buffer is written whenever an I/O function is executed. (Good for error logging.)
Writing the buffer is called flushing. That's why there is a stdio function called fflush(). You might also want to check out setvbuf() and its parameter constants, _IOFBF, _IOLBF and _IONBF. I am sure you can figure out what they mean without looking them up. ;-)
Edit: This program delivers as you originally expected:
#include <stdio.h>
// This is the header where sleep() is declared. Don't go without it.
#include <unistd.h>
int main()
{
int i=0;
// setvbuf() can be called on a stream only BEFORE
// you do any I/O on it!
setvbuf( stdout, NULL, _IONBF, 0 );
printf( "*********Testing Sleep***********\n" );
for ( i = 0; i < 10; ++i )
{
printf( "%d", i );
sleep( 1 );
}
return 0;
}
standard output for terminals is line buffered, output is not written unless there is a newline or you manually flush it.
Output is buffered, so that that the OS has an opportunity to optimize output speed. To make sure they are flushed immediately, do fflush (stdout);, but usually, you don't.
This is because printf() uses buffered output for better performance. Buffer is flushed to the console once \n is printed.
Printf is buffered.
You can force printf to 'flush' its buffer using the fflush call.
Or
Simply push the buffer to stdout using \n as in your case .
More detailed discussion is here
Related
#include <stdio.h>
#define MAXLEN 256
int main() {
int n;
char buf[MAXLEN];
while((n = read(0,buf,sizeof(buf))) != 0){
printf("n: %d:",n);
write(1,buf,n);
}
return 1;
}
The output of the program (where the first read and first write is typed by the user and echoed by the terminal) is:
read
read
write
write
n: 5:n: 6:
The output of printf comes after pressing Ctrl+D at the standard input and not along with the subsequent reads. Why does this happen?
Printf is buffered.
You can force printf to 'flush' its buffer using the fflush call:
#include <stdio.h>
#define MAXLEN 256
int main() {
int n;
char buf[MAXLEN];
while((n = read(0,buf,sizeof(buf))) != 0){
printf("n: %d:",n);
fflush(stdout); /* force it to go out */
write(1,buf,n);
}
return 1;
}
In general, printf() being buffered is a good thing. Unbuffered output, particularly to visible consoles that require screen updates and such, is slow. Slow enough that an application that is printf'ing a lot can be directly slowed down by it (especially on the Windows platform; Linux and unixes are typically impacted less).
However, printf() being buffered does bite you if you also fprintf(stderr,) - stderr is deliberately unbuffered. As a consequence, you may get your messages with some printf() missing; if you write to another FILE handle that is also associated with the terminal, and might be unbuffered, make sure you first explicitly fflush(stdout).
The manpage for fgets tells me:
It is not advisable to mix calls to input functions from the stdio
library with low-level calls to read(2) for the file descriptor associ‐
ated with the input stream; the results will be undefined and very
probably not what you want.
So the best solution would be not to to use write and printf on the same descriptor.
Printf is using stdio and it is buffered.
Push it out by sending a changing to "n: %d:\n"
You can use the std fflush() function to flush the std out buffer or you can make use of an additional \n at the end of the control string inside the printf. Something like this
printf("\n :%d:\n",n);
Its always better to use the write() & read() functions in C instead of printf() and scanf(). Printf and scanf have got some problems like printf stores the string parameter in stdout buffer. So a manual flush is required which is done through fflush function or by means of \n. In a small hello world printing program you will not find such a problem as the stdout buffer is flushed at the end of the program execution. Better use write() which works fine. scanf also have the problem of reading spaces and a lot of other problems related to stdin buffer.
For example in the code below:
main() { char a; int i=0,c; for(;i<2;i++) { scanf("%d",&c); scanf("%c",&a);} }
The above program as got the problem of reading \n into stdin on pressing enter. We could resolve this but not flushing the stdin buffer or making use of \n character. Always better to use the read() and write() functions.
Hope that helps....
Use fwrite (streams version) rather than write.
Note that, while is associated with file number 1, it isn't the same thing.
#include<stdio.h>
#include <unistd.h>
int main(){
while(1)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
On compiling this programme in gcc and on executing it only prints hello-err and not hello-out.Why is that so?Can someone please explain the reason behind it?
If you add a '\n' to your message it will (or should), ie. "hello-out\n".
The reason being is that stdout is buffered in order to be more efficient, whereas stderr doesn't buffer it's output and is more appropriate for error messages and things that need to be printed immediately.
stdout will usually be flushed when:
A newline (\n) is to be printed
You read in from stdin
fflush() is called on it
EDIT: The other thing I wanted to add before my computer crashed...twice...was that you can also use setbuf(stdout, NULL); to disable buffering of stdout. I've done that before when I've had to use write() (Unix) and didn't want my output to be buffered.
It doesn't always print out the output to stdout because by design stdout is BUFFERED output, and stderr is unbuffered. In general, the for a buffered output stream, the stream is not dumped until the system is "free" to do so. So data can continue buffering for a long while, before it gets flushed. If you want to force the buffer to flush you can do so by hand using fflush
#include<stdio.h>
#include <unistd.h>
int main(){
while(1)
{
fprintf(stdout,"hello-out");
fflush(stdout); /* force flush */
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
Update: stdout is linebuffered when connected to a terminal, and simply buffered otherwise (e.g. a redirect or a pipe)
You forgot newlines (noted \n) in your strings. Or you need to call fflush(NULL); or at least fflush(stdout); before sleep(1);
And fprintf(stdout, ...) is the same as printf(...)
You need to output newlines or to call fflush because (at least on Linux) the stdout FILE buffer is line-buffered. This means that the C library is buffering data, and will really output it (using the write Linux system call) when the buffer is full enough, or when you flush it either with a new line, or by calling fflush. Buffering is needed because system calls are costly (calling write for every byte to be output is really too slow). Read also the man page of setbuf
i want to print "CLIENT>" on stdout in c, without new line.
printf("CLIENT>");
does not print enything.
how do i solve this?
int main (){
printf("CLIENT>");
}
Try fflush(stdout); after your printf.
You can also investigate setvbuf if you find yourself calling fflush frequently and want to avoid having to call it altogether. Be aware that if you are writing lots of output to standard output then there will probably be a performance penalty to using setvbuf.
Call fflush after printf():
int main (){
printf("CLIENT>");
fflush( stdout );
}
On some compilers/runtime libraries (usually the older ones) you have to call fflush to have the data physically written:
#include <stdio.h>
int main( void )
{
printf("CLIENT>");
fflush(stdout);
return 0;
}
If the data has newline in the end, usually fflush isn't needed - even on the older systems.
#include <stdio.h>
#define MAXLEN 256
int main() {
int n;
char buf[MAXLEN];
while((n = read(0,buf,sizeof(buf))) != 0){
printf("n: %d:",n);
write(1,buf,n);
}
return 1;
}
The output of the program (where the first read and first write is typed by the user and echoed by the terminal) is:
read
read
write
write
n: 5:n: 6:
The output of printf comes after pressing Ctrl+D at the standard input and not along with the subsequent reads. Why does this happen?
Printf is buffered.
You can force printf to 'flush' its buffer using the fflush call:
#include <stdio.h>
#define MAXLEN 256
int main() {
int n;
char buf[MAXLEN];
while((n = read(0,buf,sizeof(buf))) != 0){
printf("n: %d:",n);
fflush(stdout); /* force it to go out */
write(1,buf,n);
}
return 1;
}
In general, printf() being buffered is a good thing. Unbuffered output, particularly to visible consoles that require screen updates and such, is slow. Slow enough that an application that is printf'ing a lot can be directly slowed down by it (especially on the Windows platform; Linux and unixes are typically impacted less).
However, printf() being buffered does bite you if you also fprintf(stderr,) - stderr is deliberately unbuffered. As a consequence, you may get your messages with some printf() missing; if you write to another FILE handle that is also associated with the terminal, and might be unbuffered, make sure you first explicitly fflush(stdout).
The manpage for fgets tells me:
It is not advisable to mix calls to input functions from the stdio
library with low-level calls to read(2) for the file descriptor associ‐
ated with the input stream; the results will be undefined and very
probably not what you want.
So the best solution would be not to to use write and printf on the same descriptor.
Printf is using stdio and it is buffered.
Push it out by sending a changing to "n: %d:\n"
You can use the std fflush() function to flush the std out buffer or you can make use of an additional \n at the end of the control string inside the printf. Something like this
printf("\n :%d:\n",n);
Its always better to use the write() & read() functions in C instead of printf() and scanf(). Printf and scanf have got some problems like printf stores the string parameter in stdout buffer. So a manual flush is required which is done through fflush function or by means of \n. In a small hello world printing program you will not find such a problem as the stdout buffer is flushed at the end of the program execution. Better use write() which works fine. scanf also have the problem of reading spaces and a lot of other problems related to stdin buffer.
For example in the code below:
main() { char a; int i=0,c; for(;i<2;i++) { scanf("%d",&c); scanf("%c",&a);} }
The above program as got the problem of reading \n into stdin on pressing enter. We could resolve this but not flushing the stdin buffer or making use of \n character. Always better to use the read() and write() functions.
Hope that helps....
Use fwrite (streams version) rather than write.
Note that, while is associated with file number 1, it isn't the same thing.
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");
}