#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
int main(void)
{
wiringPiSetupGpio();
for(int i = 0 ; i <50; i++)
{
if ( i%10 == 1)
{
printf("\n");
}
printf("%d ", i);
delay(1000);
}
return 0;
}
I'm working in rasberry pi environment.
I want to print a number for each 1 second. But this code did not print a number one by one but
print 10 numbers for each 10 seconds. This code gives 10 numbers in line at once. What's the problem??
The stdout channel is line buffered by default. This means that data sent to stdout won't necessarily appear until a newline character is printed.
If you call fflush(stdout), any buffered output will be immediately printed.
printf("%d ", i);
fflush(stdout);
in order to print the values at the running time using printf you need to add \n so try this may work.
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
int main(void)
{
wiringPiSetupGpio();
for(int i = 0 ; i <50; i++)
{
if ( i%10 == 1)
{
printf("\n");
}
// a `\n` added at the end of the string!
printf("%d \n", i);
delay(1000);
}
return 0;
}
for more info read this question's answer
The problem is probably that the output stream is not being flushed. I suggest that you call fflush( stdout ); before the delay(1000); function call. This will ensure that all printed data actually becomes observable, before the program enters a wait state.
Normally, it is not necessary to explicitly flush an output stream, because the output will become visible sooner or later. For example, the output buffer will usually get implicitly flushed whenever you read input or when the program ends. Also, if your program is writing output to the user's screen (in contrast to, for example, writing output to a file), then the output stream is probably line-buffered, which means that the output stream will get implicitly flushed whenever a newline character is written.
However, in this case, it appears that the implicit flushing mentioned above is not sufficient. Therefore, you will have to revert to explicit flushing using the function fflush, as mentioned above.
Related
This program does not terminate nor does it let me input any values, simply a black screen with no output.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int size;
printf("Enter number of elements in array:");
scanf("%d", &size);
printf("\n%d\n", size);
return 0;
}
Sounds like you're suffering from buffering. Add
fflush(stdout);
after the printf line.
By default, if stdout goes to a terminal, it is line buffered, meaning output is only actually written when the buffer is full or when you output a newline (\n). Terminating the program (via exit() or returning from main) closes all open file handles and also forces a flush.
To make sure output is generated right then and there, call fflush.
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);
}
My friend gave me a riddle. I run it. but not getting expected output.
Code is:
#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
the output doesn't printing hello-out.
Instead it's printing like this infinitely:
hello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-err
Then I tried like this:
#include <stdio.h>
#include <unistd.h>
int main()
{
int i = 0;
while(i <= 5)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
i++;
}
return 0;
}
the optput is:
hello-errhello-errhello-errhello-errhello-errhello-errhello-outhello-outhello-outhello-outhello-outhello-out
In C language instructions execute line by line. But why it is not following here?
File IO behavior is determined by the system and if you want to keep that order you must explicitly fflush. See this program below:
while(i <= 5)
{
fprintf(stdout,"hello-out");
fflush(stdout);
fprintf(stderr,"hello-err");
fflush(stderr);
sleep(1);
i++;
}
The reason is output buffering.
By default, stdout is buffered: if it's connected to a terminal it's line-buffered, otherwise it's fully-buffered. When it's line-buffered, that means that nothing is printed until you print a newline, the buffer fills up, or the buffer is flushed explicitly. Since you're not printing newlines, the output doesn't show up until the program exits, because all stdio buffers are flushed at that time.
stderr, on the other hand, is not buffered by default. So anything written to it appears immediately.
So my problem is my program runs too fast that I can't see how it behaves. It's supposed to make the text crawl along the edges of the terminal. I tried to use sleep() to make a short pause betweenprintf(...)s so that it I can see where the text us going while it prints.
This is what it looks like:
http://i.imgur.com/B6FFbNp.gif
So I put sleep() function after the printfs so that it will pause before starting the loop again and make the text move slowly. But what happens is it pauses the programs indefinitely before it even starts. This also happens with usleep and system("pause 1"). This is what it looks like:
http://i.imgur.com/krGW3lB.gif
==================================================================================
EDIT:
Okay, I figured it out on my own. It seems that sleep() only works if I put \n in my strings. I don't know why. I didn't even read this in the damn manuals.
So if you have
printf("HELLO\n");
sleep(3);
printf("HELLO\n");
sleep(3);
printf("HELLO\n");
It will result in:
HELLO
[pause for 3 seconds]
HELLO
[pause for 3 seconds]
HELLO
but if you remove the newline characters it will:
[pause for 9 seconds]
HELLO HELLO HELLO
I don't know why this happens but it just does
==================================================================================
EDIT:
This is how I wanted my program to work:
http://i.imgur.com/DXv7E60.gif
Thank you for your answers
Your observations do not due to sleep() not working, but to the fact that printf() uses stdout, which is line buffered. "line buffered" means, that what has been written to stdoutis buffered until the end of the line is reached before the buffer's content it is flushed out.
So after the first printf("HELLO"); the output does not go to the screen but stays in the buffer, then sleep(1); is executed and makes you wait. Then for the next printf("HELLO"); the output still does not go to the screen, but the following sleep(1); again makes you wait for 1 second ... and so on until a line end if reached by your program printing a '\n' or by the program's end, which implicitly flushes the output buffer to the console.
You can avoid the behaviour by flushing stdout's output buffer explicitly after every printf():
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf("HELLO");
fflush(stdout);
sleep(3);
printf("HELLO");
fflush(stdout);
sleep(3);
printf("HELLO");
/* fflush(stdout); */ /* not needed as buffers are implicitly flushed on the program's end */
return 0;
}
A quick hack I usually do is make some buffer array (eg. char buf[10]) and place an fgets() in between iterations, which forces the program to wait for a newline from the user. So, for example, if we had:
.
.
.
for(i = 0; i < 1000000; ++i)
printf("%d\n", i);
we could then do
.
.
.
char buf[10];
for(i = 0; i < 1000000; ++i){
printf("%d\n", i);
fgets(buf, 10, stdin);
}
and control the iterations with the enter key.
We could also stop every nth iteration by using a modulus. Using the above example, we will now stop every 100 iterations:
.
.
.
char buf[10];
for(i = 0; i < 1000000; ++i){
printf("%d\n", i);
if(i % 100 == 0)
fgets(buf, 10, stdin);
}
A more time consuming but effecient way is to use a dedicated debugger like GDB.
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