Why do std::cout and printf() not print between usleep() delays? - usleep

i have a program that is supposed to print "Hello, World!" in slowly scrolling text. I am using the unistd.h library for the usleep() function, and i'm using std::cout to print the characters to the standard output:
#include <iostream>
#include <stdio.h>
#include <unistd.h>
char hello[13]={'H','e','l','l','o',',',' ','W','o','r','l','d'};
int main (){
for(int i=0; i<14; i++){
std::cout<<hello[i]; //it prints the entire string after
usleep(100000); //100000 ms, but it should print a char after
} //every 100 ms.
}

You might need to flush the output stream.

Related

Why the command \r in printf() doesn't work?

I'm trying to update a text on the terminal without have to print again the text. Right now I'm trying to do it on a simple code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]){
for(int i=0;i<=100;++i){
printf("\r[%3d%%]",i);
sleep(1);
}
printf("\n");
return 0;
}
The code literally print nothing, with the pointer blinking at the start of the line.
Can someone help me?
The standard output stream is typically line buffered, so if you don't print a newline (i.e. \n) then the output will remain in the buffer.
After calling printf, call fflush(stdout);. This will flush the standard output stream so that you can see the text.

Illegal Instruction :4

i was writing a c code for executing "history 10" command of terminal,i run program using clang compiler on my mac terminal,it show error "Illegal Instruction :4"
My Code is-
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include<errno.h>
#include<sys/wait.h>
#include <unistd.h>
#include<string.h>
int main()
{ char cmd[10];
strcpy(cmd,"history 10");
system(cmd);
return 0;
}
You overrun your buffer: the cmd array has only 10 characters and you strcpy an 11-character string into it (the string has an implicit 11-th zero byte at the end, which is the string's terminator).
Get rid of the buffer and just do
system("history 10");
Or declare the buffer long enough to accomodate your current, and possibly some future command. Something like this:
char cmd[500];

Termcap "cl" command doesn't clear screen

I can't seem to get termcap's "cl" command to work, but the terminal escape code does.
For example:
#include <termcap.h>
#include <stdio.h>
int main()
{
tputs(tgetstr("cl", NULL), 1, putchar);
}
This doesn't change the terminal. But when I run:
#include <stdio.h>
int main()
{
printf("\e[2J");
}
or if I call echo `tput cl`
The terminal is cleared.
Why does this happen? Shouldn't termcap give that same escape code?
EDIT: Fixed writing characters
EDIT2: It's because i didn't call tgetent() before calling tgetstr(). Thanks guys!
Before interrogating with tgetstr(), you need to find the description of the user's terminal with tgetent():
#include <stdio.h>
#include <stdlib.h> // getenv
#include <termcap.h> // tgetent tgetstr
int main(void)
{
char buf[1024];
char *str;
tgetent(buf, getenv("TERM"));
str = tgetstr("cl", NULL);
fputs(str, stdout);
return 0;
}
Compile with -ltermcap

Instant write buffer to stdout

Is possible to write a large block of text into stdout all at once.
For instance, I get a 50kb text file and put it into story.txt. I am curious if I can dump the contents of this file into stdout without the user noticing any text slowly coming in. One moment there is no text, next the whole buffer is flushed into stdout.
I was trying to do it with the following code but no matter what buffering mode I set it didn't manage to write the file all at once, only in parts.
/* dumps a lot of text at once */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
char story[100000];
char buffer[100000];
int main(int argc, char **argv)
{
FILE *handle = fopen("coolstory.txt", "r");
size_t n = fread(&story[0], 1, 100000, handle);
fclose(handle);
/* try to flush all at once... */
fclose(stdout);
freopen("/dev/tty", "w", stdout);
setvbuf(stdout, &buffer[0], _IOFBF, 100000);
fwrite(story, n, 1, stdout);
fflush(stdout);
printf("\nread %u bytes.\n", n);
return 0;
}
The reopen part was me wondering if setvbuf/flush would behave differently if I called them right after the stdout was opened. Unfortunately it did nothing.
I just want to know whether it is possible, and if not, why.
I'm on ubuntu linux 14.04.
Note: it is usually a bad idea to #include header files that are not used.
I ran this version of the code:
/* dumps a lot of text at once */
//#include <unistd.h>
#include <stdio.h>
//#include <stdlib.h>
//#include <fcntl.h>
//#include <string.h>
char story[100000];
int main( void )
{
FILE *handle = fopen("value_chainLength.txt", "r");
size_t n = fread(story, 1, 100000, handle);
fclose(handle);
fwrite(story, n, 1, stdout);
fflush(stdout);
printf("\nread %lu bytes.\n", (long unsigned)n);
return 0;
}
on a 46550749 byte text file
The output was done on a terminal almost as fast as I could press and release the 'enter' key.
the last line output was:
read 100000 bytes.
I did notice ever so slight a hesitation before printing the last line, all the lines before that point were practically instantaneous.

Wrong printing when using signal handler

I have encountered problems on signal handling when writing a shell-like program on C.
Here is the simplified version of my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#define SIZE 255
void sig_handler(int sig){
if (sig == SIGINT)
printf("\n[shell]$\n");
}
int main()
{
char input[SIZE];
printf("[shell]$");
signal(SIGINT,sig_handler);
while( gets(input) != NULL ){
// code of the shell including command interpreter and command execution
printf("[shell]$");
}
return 0;
}
When I run the program and try out SIGINT with command - "cat", the output shows as the following:
[shell]$ ^C (ctrl+C pressed for the first time)
[shell]$
^C (the input position go to the next line, which is unwanted)
[shell]$
cat (I want it in the same line with [shell]$)
^C
[shell]$
[shell]$ (duplicate printing occurs)
I have tried to modify the function void sig_handler(int sig) by deleting the second \n. However, the situation becomes worse than before. The program doesn't automatically trigger the signal event on the first pressing of ctrl+C.
To clarify my problem, here are the two questions I ask:
1. How to make the input position on the same line with [shell]$ ?
2. How to solve the duplicate printing problem ?
What #zneak said is true, you can use fflush and delete the second \n in sig_handler,
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#define SIZE 255
void sig_handler(int sig){
if (sig == SIGINT)
printf("\n[shell]$");
fflush(stdout);
}
int main()
{
char input[SIZE];
printf("[shell]$");
fflush(stdout);
signal(SIGINT,sig_handler);
while( gets(input) != NULL ){
// code of the shell including command interpreter and command execution
printf("[shell]$");
}
return 0;
}
First and foremost, printing from signal handler is a bad idea. Signal handler is like an interrupt handler - it happens asynchronously, it could be raised while being inside your standard library code and calling another stdlib routine might mess up with non-reentrant internals of it (imagine catching SIGINT while inside of printf() in your loop).
If you really want to output something from within, you better use raw write() call to stderr file descriptor.

Resources