I've been trying to print to the terminal with a pause, it's better explained with the following code:
I'm trying to have X print to the terminal and then wait 5s and have X print again but when I run the code, it waits 5s and prints XX can anyone help me get the proper functionality?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static void sleepMs(long long delayMs){
const long long NS_PER_MS = 1000 * 1000;
const long long NS_PER_SECOND = 1000000000;
long long delayNs = delayMs * NS_PER_MS;
int seconds = delayNs / NS_PER_SECOND;
int nanoSeconds = delayNs % NS_PER_SECOND;
struct timespec reqDelay = {seconds, nanoSeconds};
nanosleep(&reqDelay, (struct timespec *) NULL);
}
int main()
{
printf("X");
sleepMs(5000);
printf("X");
return 0;
}
Thank you in advance, sorry for any missing tags.
EDIT: I want them to print on the same line
You need to flush the output stream if you want to see the result before printing a \n:
putchar('X');
fflush(stdout);
I am a C beginner and trying this and that.
I want to display a string letter by letter with tiny pauses in between. So my idea was a small pause using sleep or usleep after displaying each char but I read that using nanosleep in your own function makes more sense. So I put my little pauses in a function "msleep" to get microseconds pauses.
I output my string 3 times.
Once in the main(), then in a do-while-loop in a function (fancyOutput) char by char, and eventually in the same function with printf again to check, if it was handled over correctly.
My problem: I expected, that the middle output would work char by char and separated by 100/1000 seconds breaks, but what I experience is a long break before chowing any char and then a fast output if line two and three. It looks like the compiler "realized what I am planning to do and wants to modify the code to be more efficient." So all my pauses seemed to be combined in one long break.
Maybe you remeber the captions in the tv series "x files" - something like that I want to produce.
For sure there are better and more sophisticated ways to archieve what I am going to try but I want to learn and understand what is going on. Can someone help me with that?
I am using codeclocks on a debian-based distro with gcc.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
You are getting problem with buffer.
When you use printf with no \n (new line) C is buffering the display in order to display information block by block (to optimize displaying speed).
Then you need to either add a \n to your printf or add a flush of the stdout.
An other solution will be to use stderr, which got no buffer, but stderr is meant for error not output :)
You can also check setvbuf in order to change the buffering.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int msleep(long tms);
void fancyOutput(char inputToOutput[]);
int msleep(long tms)
{
struct timespec ts;
int ret;
if (tms < 0)
{
return -1;
}
ts.tv_sec = tms / 1000;
ts.tv_nsec = (tms % 1000) * 1000000;
do
{
// printf("sleeping for %d", ret);
ret = nanosleep(&ts, &ts);
}
while (ret);
return ret;
}
void fancyOutput(char inputToOutput[])
{
int counter = 0;
do
{
printf("%c", inputToOutput[counter]);
flush(stdout);
msleep(100);
++counter;
}
while (!(inputToOutput[counter]=='\0'));
printf("\n");
printf("%s\n", inputToOutput); // only check, if string was properly handled over to function
}
char output[] = "This string shall appear char by char in the console.";
void main(void)
{
printf("%s\n", output); // only check, if string was properly set and initialized
fancyOutput(output); // here the function above is called to output the string char by cchar with tiny pauses between
}
So, I tried the solution to place fflush(stdout); directly after the char-output in the loop. It worked as intended.
Summarizing for those with similar problems (guess this also happens with usleep and similar self-made functions):
As I understaood, printf "collects" data in stdout until it "sees" \n, which indicates the end of a line. Then printf "releases" stdout. So in my initial post it "kept" each single char in stdout, made a pause after each char and finally released stdout in one fast output.
So fflush(stdout); after each char output via empties stdout char by char.
Hope it can help others.
Okay, so I am working on a project right now, and the project is to create a game. Here is the concept below:
Please press any key to begin!
Press the ‘h’ key!
You have 2500 milliseconds to respond!
Press the ‘c’ key!
You have 2400 milliseconds to respond!
Press the ‘k’ key!
You have 2300 milliseconds to respond!
Wrong key! :(
You lose!
You made it through 3 rounds!
Here is the code I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
/*----------------------------------------------------------------------------
- Prototypes -
-----------------------------------------------------------------------------*/
char random1 ();
int cmpChar(char rand2, char user1);
/*----------------------------------------------------------------------------
- Implementation -
-----------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
srand(time(NULL)); /* This will ensure a random game each time. */
time_t cdt;
time(&cdt);
ctime(&cdt);
printf("%s\n", ctime(&cdt));
char ans, randChar;
int gameCont = 1;
int score = 0;
printf("This is a Bop-It Game!\n");
printf("\nPress any key to start\n");
getch();
int i = 2600;
while(gameCont == 1){
randChar = random1();
printf("press the '%c' key!\n", randChar);
ans = getch();
gameCont = cmpChar(randChar, ans);
if (gameCont == 1){
score++;
i -= 100;
printf("You have %d milliseconds to respond!\n", i);
}
}
printf("Your score was %d!\n", score);
return 0;
}
char random1 (){
char randInput;
randInput = (rand()%(122-90)+90);
return randInput;
}
int cmpChar(char rand2, char user1){
if (user1 == rand2){
return 1;
}
if (user1 != rand2){
printf("That is incorrect\n");}
else{
return 0;
}
}
If you can see, I implemented a code that kind of mimics the countdown millisecond thing, but it doesnt actually use a timer, it just uses a loop and print statements.
Im on windows OS, and am trying to use #include <sys/time.h> to create a way to implement a timer, and also have it decrease by 100 milliseconds after each iteration.
If you can help with the whole implementation, great, otherwise just a nudge in the right direction would be greatly appreciated.
summary : system("clear"); isn't working well.
I'm using gcc, ubuntu 18.04 LTS version for c programming.
what I intended was "read each words and print from two text files. After finish read file, delay 3 seconds and erase terminal"
so I was make two text files, and using system("clear"); to erase terminal.
here is whole code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void printFiles(char *file1,char *file2,char *change1, char *change2){
FILE *f;
char *text = malloc(sizeof(char)*100);
f=fopen(file1,"r");
system("clear");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
//fscanf(f,"%s", text);
printf("%s ",text);
//usleep(20000);
}
//sleep(3);
fclose(f);
printf("\n");
//all comment problems are appear here. and if I give delay, such as usleep() or sleep, delay also appear here. Not appear each wrote part.
f=fopen(file2,"r");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
if(strcmp(text,"**,")==0){
strcpy(text,change1);
strcat(text,",");
}
else if(strcmp(text,"**")==0){
strcpy(text,change1);
}
else if(strcmp(text,"##.")==0){
strcpy(text,change2);
strcat(text,".");
}
else if(strcmp(text,"##,")==0){
strcpy(text,change2);
strcat(text,",");
}
printf("%s ",text);
//usleep(200000);
}
fclose(f);
free(text);
sleep(3); //here is problem. This part works in the above commented part "//all comment problems are appear here."
system("clear"); //here is problem. This part works in the above commented part "//all comment problems are appear here."
}
int main(){
char file1[100] = "./file1.txt";
char file2[100] = "./file2.txt";
char change1[100]="text1";
char change2[100]="text2";
printFiles(file1,file2,change1,change2);
return 0;
}
I'm very sorry, files and variables names are changed because of policy. Also, file contents also can not upload.
I can't find which part makes break Procedure-oriented programming. I think that was compiler error, because using one file read and system(clear); works well.
I also make two point variables, such as 'FILE *f1; FILE *f2; f1=fopen(file1); f2=fopen(file2)...`, but same result occur.
Is it compiler error? If it is, what should I do for fix these problem? Thanks.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void printFiles(char *file1,char *file2,char *change1, char *change2){
FILE *f;
char *text = malloc(sizeof(char)*100);
f=fopen(file1,"r");
system("clear");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
//fscanf(f,"%s", text);
printf("%s ",text);
fflush(stdout);
//usleep(20000);
}
//sleep(3);
fclose(f);
printf("\n");
//all comment problems are appear here. and if I give delay, such as usleep() or sleep, delay also appear here. Not appear each wrote part.
f=fopen(file2,"r");
//while(!feof(f)){
while(EOF!=fscanf(f,"%s",text)){
if(strcmp(text,"**,")==0){
strcpy(text,change1);
strcat(text,",");
}
else if(strcmp(text,"**")==0){
strcpy(text,change1);
}
else if(strcmp(text,"##.")==0){
strcpy(text,change2);
strcat(text,".");
}
else if(strcmp(text,"##,")==0){
strcpy(text,change2);
strcat(text,",");
}
printf("%s ",text);
fflush(stdout);// The answer.
//usleep(200000);
}
fclose(f);
free(text);
sleep(3); //here is problem. This part works in the above commented part "//all comment problems are appear here."
system("clear"); //here is problem. This part works in the above commented part "//all comment problems are appear here."
}
int main(){
char file1[100] = "./file1.txt";
char file2[100] = "./file2.txt";
char change1[100]="text1";
char change2[100]="text2";
printFiles(file1,file2,change1,change2);
return 0;
}
Hint for
That's probably just buffering. Do fflush(stdout); before you sleep. – melpomene
Thanks.
You can try this solution for delay.
#include <time.h>
#include <stdio.h>
void delay(double seconds)
{
const time_t start = time(NULL);
time_t current;
do
{
time(¤t);
} while(difftime(current, start) < seconds);
}
int main(void)
{
printf("Just waiting...\n");
delay(3);
printf("...oh man, waiting for so long...\n");
return 0;
}
Following solution is pretty quite the same of previous one but with a clear terminal solution.
#include <time.h>
#include <stdio.h>
#ifdef _WIN32
#define CLEAR_SCREEN system ("cls");
#else
#define CLEAR_SCREEN puts("\x1b[H\x1b[2J");
#endif
void delay(double seconds)
{
const time_t start = time(NULL);
time_t current;
do
{
time(¤t);
} while(difftime(current, start) < seconds);
}
int main(void)
{
printf("Just waiting...\n");
delay(2); //seconds
printf("...oh man, waiting for so long...\n");
delay(1);
CLEAR_SCREEN
return 0;
}
I've a simple C function which I call from GoLang. In my C function I'm using gettimeofday function. I understand that this function doesn't give accurate time and I'm okay with that as I only need to get some idea. I just want to get the time difference to run a big for loop.When I run the C function from a C program, it works fine. The for loop takes around 3 seconds to finish. But if I call the same function from GoLang, it looks like that it doesn't take any time in the for loop The program finishes immediately.
Here goes my code.
timetest.h
#include <sys/time.h>
#include<stdio.h>
int TimeTest(){
int i=0;
int j = 1000000000;
unsigned long long startMilli=0;
unsigned long long endMilli=0;
struct timeval te;
gettimeofday(&te, NULL);
startMilli = te.tv_sec*1000LL + te.tv_usec/1000;
for (i=0; i<1000000000; i++){
if (j-1 == i){
printf("matched\n");
}
}
gettimeofday(&te, NULL);
endMilli = te.tv_sec*1000LL + te.tv_usec/1000;
printf("Start = %d End = %d Total time %d\n", startMilli, endMilli, endMilli - startMilli);
return endMilli - startMilli;
}
test.go
package main
// #include <sys/time.h>
// #include "timetest.h"
import "C"
import (
"fmt"
)
func main(){
diff := C.TimeTest()
fmt.Println(diff)
}
Main.c
#include"timetest.h"
int main(){
int diff = TimeTest();
printf("%d\n", diff);
return 0;
}