Timer using a time function in C [duplicate] - c

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 1 year ago.
I want to print a line and then get it erased after ten seconds.
So I thought that I should write a timer as a preliminary programme and with erasure I could deal later using whatever I find on the internet (using \r for example).
And so I want to print "I love nachos" and ten seconds later "I hate nachos".
However, even though printf("I love nachos") is written before any conditions, the programme prints both strings after ten seconds.
#include <stdio.h>
#include <time.h>
int main(void) {
printf("I love nachos");
time_t now = time(NULL);
while (1)
{
time_t future = time(NULL);
if ((future-now)==10)
{
break;
}
}
printf("I hate nachos");
return 0;
}
I asked my friend to tackle the problem and he wrote:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
printf("Start\n");
time_t t0 = time(NULL);
while ( (difftime(time(NULL), t0)) <= 10.0 )
{}
printf("End");
return 0;
}
However, in that case the programme only works with \n in printf("Start\n").
If I remove \n I get the same result as per my initial code and I obviously don't want \n there, because I wouldn't be able to erase the line with \r

The printf output to stdout is by default line buffered. That means nothing is actually sent out until either the internal buffer is full or a newline is added or the FILE is closed (as happens implicitly when the program exits)
So either add a newline or use fflush to force the buffer to be transmitted immediately to the output.

Related

Why do I need "\n" in c, when using the sleep function? [duplicate]

This question already has answers here:
What is it with printf() sending output to buffer?
(3 answers)
Closed 1 year ago.
My code:
#include <stdio.h>
#include <unistd.h>
int main(){
printf("I sleep\n");
sleep(3);
printf("\033[H\033[J");
return 0;
}
if I don't write "\n" in the printf-function, "I sleep" wil not be displayed, until sleep(3) is done.
Can someone explain? Thanks!
The standard output stream, when not outputting to a file or device, is line-buffered by default on most UNIX-like systems.
That mean that text sent there typically won't actually be printed until a newline character is encountered.

"\r" in C stops output before it [duplicate]

This question already has answers here:
Why does printf() not print anything before sleep()?
(4 answers)
Closed 1 year ago.
I wrote a piece of code like this:
#include <stdio.h>
#include <unistd.h>
int main() {
printf("one");
sleep(1);
printf("\r");
printf("two");
return 0;
}
It was supposed to first print "one", and then override it by "two" after one second's pause.
But what really happened is that it only print "two" after one second's empty, without printing "one" first. I am confused, can someone figure it out? Thanks a lot.
The statement printf("one") does not immediately print "one" to the terminal, but it writes the string to the standard output stream (stdout) - which is usually buffered. Only when this stream is flushed, do its contents get printed to the terminal. Usually, this happens whenever a newline is printed or when the program exits, among other conditions.
The output stream can be forced to flush by calling fflush(stdout), which produces the desired result:
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("one");
fflush(stdout); // Line added
sleep(1);
printf("\r");
printf("two");
return 0;
}
See fflush for more information. The buffering mode of a stream can be set using the setvbuf function.
Also, note that the usual main signature, when using no parameters, is int main(void).
Acknowledgements: Thanks to Andreas Wenzel for a correction and the setvbuf addition.

why system function execute first [duplicate]

This question already has answers here:
in c system() executes before printf() even when printf come first [duplicate]
(1 answer)
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 1 year ago.
the problem is when i run this code the system function start first and as per my understanding (which is very little), printf function should start first then the system function !
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("test1");
system("echo 'test2'");
}
and it output :
test2
test1
but the output should be like this instead!
test1
test2
You have to add a line break (\n) to the printf statement. I can only give you my basic (probably not entirely correct) explanation. printf gives the characters to a buffer for printing to the console. This buffer is then printed per line. If you add the \n the line is printed instantly.
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("test1\n");
system("echo 'test2'");
}
i just find the explination its when we say printf is actually what we call buffered the output that we ask to print to standard out in this case our display doesn't come to the display immediately it goes into a holding pool a buffer and when that buffer gets filled up it'll dump everything out at once it's an efficiency consideration but if we print out a new line that \n it will go ahead and it will flush the buffer out right ,so to fix it we can use :
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("test1\n");
system("echo 'test2'");
}
or :
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("test1");
fflush(stdout);
system("echo 'test2'");
}
both do the same job (flush the output buffer).

How do I implement the sleep function in my for loop correctly? (Ubuntu)

I'm trying to make my code print something to the screen, then wait 1 second, then go around the for loop and print it again 21 times. It works when I do this in Windows in CodeBlocks by using #include and then Sleep(1000). But when I'm doing it on my Ubuntu VM by using #include and sleep(1), everything disappears from my terminal for 21 seconds then all appears at once. I think I'm using the wrong function or something.
Any ideas?
This is the code in Ubuntu terminal which ends up removing everything already on my terminal, waits 21 seconds then just prints "Hello" 21 times.
#include <stdio.h>
#include <unistd.h>
int main()
{
for (int i = 0; i < 21; i++)
{
printf("Hello");
sleep(1);
}
}
This is the code in Windows which prints "Hello" every second for 21 seconds therefore printing 21 Hello's on my screen over 21 seconds. Which is what I'm trying to achieve in my Ubuntu VM.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main() {
for (int i = 0; i < 21; i++)
{
printf("Hello");
Sleep(1000);
}
return 0;
}
In UNIX, process streams buffer - they accumulate I/O and do not "flush" to the underlying device immediately on write, per default. So - you need to flush the stream:
#include <stdio.h>
#include <unistd.h>
int main()
{
for (int i = 0; i < 21; i++)
{
printf("Hello");
fflush(stdout);
sleep(1);
}
}
It would also work if you output a newline '\n' after "Hello", I believe.
printf output is buffered - which means, it is not guaranteed to appear on the screen immediately. Rather, it appears when one of the following happens:
when the buffer becomes full, - at which time the old contents of buffer is displayed to the screen and the buffer is cleared fresh for the new output - this is called buffer flushing
when the application terminates - which forces flushing of all the printf buffers, and this is what you see on the screen
When buffer is flushed by the programmer.
The last case is most interesting for you, and there are two ways you can do this - either include \n (new line) control character in your string, like
printf("Hello\n");
or call fflush for stdout stream, like
printf("Hello");
fflush(stdout);

How to delete random number sequence

I am new to C programming.
I am trying to work through an example in my textbook.
Problem:
1 : Can't make random number generator pause for one second, without having to
insert printf(); in a place where I shouldn't.
2: Can't make the program pause for 1 second, and then delete random sequence. I have tried using printf(\r), but it just deletes the entire sequence without pausing for 1 second.
Help appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
time_t Start_Of_Seq = (time(NULL));
time_t Now = 0;
Now = clock();
srand((unsigned int)Start_Of_Seq);
for(int i = 1; i <= 5; i++)
{
printf("%d",rand()% 10);
}
printf("\n"); //This shouldn't be here.
for(; clock() - Now < CLOCKS_PER_SEC;);
printf("Testing the to see if there is a pause\n");
}
The printf function outputs everything to a buffer. The buffer is actually printed only after a newline. Try fflush(stdout); to print the buffer contents immediately.
Besides, if you use Linux or another Unix-like system, for pauses there is a system call sleep. Try the man 3 sleep command to see more info.

Resources