Raspberry Pi: printf() doesn't work with wiringPi - c

I'm trying a simple code that using wiringPi as here:
#include<wiringPi.h>
#include<stdio.h>
int main(void){
int i;
wirintPiSetup();
pinMode(0,OUTPUT); //a single LED
pinMode(8,INPUT); //tactile switch
for(;;){
delay(500);
//push tactile switch and LED is turning on
if(digitalRead(8)) digitalWrite(0,0);
else digitalWrite(0,1);
printf("%d",digitalRead(8));
}
}
I expected a result of printf() is output to console,
but it doesn't work.
printf() couldn't run in same time with wiringPi APIs?
no warnings at compile. and CPU consumption is always under 4%.
running on Raspbian.
Thanks for your time!

stdout by default is typically line-buffered, meaning it tries to put off writing data to the underlying file until a newline. But since you never print a newline, stdout will just buffer your text until it runs out of space.
You can fix this by either adding a newline in the format string (i.e. "%d\n"), or calling fflush on stdout after printing.

Related

Can printf write to terminal without flushing stdout?

#include <stdio.h>
int main(){
char a[2] = {0};
a[0] = 't';
printf("%s", a);
scanf("%c", a);
return 0;
}
scanf here will cause an automatic flush of stdout.
Running a.out will print t on the terminal before running scanf, more info: How is printf getting flushed before scanf is executed?
However, doing a.out > out.txt and terminating it with ^C does not print anything inside out.txt yet the output still appeared on the screen without redirecting stdout with >.
If stdout is being flushed then why out.txt is still empty?
If it's not being flushed then how did t appear on the screen in the first example?
(I know using \n or a manual fflush or properly terminating the program will fix the issue, i'm just curious about this behaviour).
The key is the word interactive:
The input and output dynamics of interactive devices shall take place as specified in 7.21.3.
As soon as you redirect the standard output to a file, it is no longer interactive.
For example the Linux C standard library actually executes the analogue of the isatty library call to figure this out. If it figures out that standard output is not directed to file it will also break this relationship. It will also increase the I/O performance of programs that work as part of a command pipeline.
You can yourself test whether stdout is connected to a terminal by executing
#include <unistd.h>
printf("stdout is connected to a terminal: %d\n", isatty(fileno(stdout)));

Printf not working with scanf

Hi i am new to the programing and for example in my code:
#include <stdio.h>
int main (void){
int a;
printf("Write a number: ");
scanf("%d", &a);
printf("Your written number was: %d", a);
return 0;
}
Printf does not write "write a number" in console when i start the program but only after i already inserted the number and pressed enter.
I have already done some research and found out for this code:
setvbuf(stdout, NULL, _IONBF, 0);
when i paste this into my program it works as it should but i am wondering why do i have to do that?
when i paste this into my program it works as it should but i am
wondering why do i have to do that?
It's because printf() is usually line-buffered when attached to a terminal. So disabling the buffering with the call to setvbuf() makes stdio library to not buffer at all.
You can also use fflush(stdout); after the printf() call to flush out the buffered output. The same can be done with setbuf(stdout, NULL); as well.
You can also add a \n at the end of printf() statement to force the flushing. But this will work only if the output goes to a terminal device.
For example, if you do (on a unix-like system):
./a.out > output_file
then the \n will not flush the buffer.
Out of the two options (setbuf() and fflush()),fflush(stdout); is probably the better option in most cases. Since disabling the buffering completely can have negative impact on performance (which is the primary reason for buffering in the first place) whereas fflush() can be judiciously used at the right place when you think it's necessary.
printf has a buffer. It is a mechanism to make code run faster by not having to switch between the user context and the kernel context. To get over this you can tell the code to flush the buffer - i.e. send it to the operating system. This can be done by
fflush(stdout);
After a printf. If the printf contains a new line this is done automatically.
You probably want \n in each of those printf statements.
Add linefeed "\n" to your printf lines like so:
printf("Write a number: \n");

buffering behaviour of stdout in c

When I run the first code and press ctrl-c immediately there will be no 45 written out to the file. But when I run the second code, I do get 45.
I couldn't come to the reason why this behavior happens in the below code? If stdout is line buffered shouldn't output come after I enter a character? What am I missing?
First code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp=stdout;
fp=fopen("myfile","w");
fprintf(fp,"%d",45);
getchar();
// return 0;
}
Second code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp=stdout;
fprintf(fp,"%d",45);
getchar();
// return 0;
}
PS: I'm using GCC and the platform is Linux.
I dont think getchar has anything to do with the buffering you are observing in the first code. If you dont press any character and wait for a while ( ie stay inside getchar() ), you'll most probably see an empty file. This happens irrespective of whether you've stalled the program with getchar, sleep or a while(1).
Now you press Ctrl-C for which your program has no handler registered and hence your program terminates abruptly. Whether buffers/streams are flushed on abrupt program termination is implementation defined. Read the full story here
Why is data not being flushed to file on process exit?
For example, on my system ( Windows 7, Code Blocks which uses gcc and mingw framework internally ), I can see 45 indeed being flushed into the file irrespective of using getchar or anything when I terminate it abruptly. ie on my system, the implementation is flushing data to the file on abrupt program termination.
So, the bottom line is, what happens when you do things in a non-normal fashion is implementation defined!
But the second case is indeed a curious one where getchar seems to be flushing the stdout buffer. I shall update on that as soon as I find the exact cause of why getchar is/seems-to-be flushing stdout buffer
Whats causing confusion is getchar(), seems like when it is called it is flushing stdout.
If you replace getchar() with something like sleep(10) then you 45 won't be printed.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
FILE *fp=stdout;
//fp=fopen("myfile","w");
fprintf(fp,"%d",45);
sleep(10);
//getchar();
// return 0;
}
The first case you are writing to a physical file. fopen, fclose are buffered I/O depends on the implementation, data may not be committed immediately until the buffer is full. Calling fclose() will cause the buffer to be written to disk.
The second case you are writing to STDIO and data written to STDIO normally show up immediately.

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 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