I was wondering how can I insert an empty space in the string text (defined in char *text = argv[1];)
For example, if a write:
./mar "Hello how are you"
I would like to see/
Hello how are you Hello how are you Hello how are you Hello how are you
and not
Hello how are youHello how are youHello how are youHello how are youHello how are you
scrolling horizontally in the cli.
The code is:
/*mar.c*/
#include <curses.h>
#include <unistd.h> // For sleep()
#include <string.h> // For strlen()
#include <stdlib.h> // For malloc()
#include <sys/select.h>
int main(int argc, char* argv[])
{
char *text = argv[1];
char *scroll;
int text_length;
int i,p, max_x, max_y;
// Get text length
text_length = strlen(text);
// Initialize screen for ncurses
initscr();
// Don't show cursor
curs_set(0);
// Clear the screen
clear();
// Get terminal dimensions
getmaxyx(stdscr, max_y, max_x);
scroll = malloc(2 * max_x + 1);
for (i=0; i< 2*max_x; i++) {
getmaxyx(stdscr, max_y, max_x);
scroll[i] = text[i % text_length];
}
scroll[2*max_x - 1]='\0';
// Scroll text back across the screen
p=0;
do{
getmaxyx(stdscr, max_y, max_x);
mvaddnstr(0,0,&scroll[p%max_x], max_x);
refresh();
usleep(40000);
p=p+1;
// Execute while none key is pressed
}while (!kbhit());
endwin();
return 0;
}
int kbhit(void)
{
struct timeval tv;
fd_set read_fd;
tv.tv_sec=0;
tv.tv_usec=0;
FD_ZERO(&read_fd);
FD_SET(0,&read_fd);
if(select(1, &read_fd, NULL, NULL, &tv) == -1)
return 0;
if(FD_ISSET(0,&read_fd))
return 1;
return 0;
}
You need to allocate a new
char
array whose length is 2 bytes greater than the length of the argument string (so that there's room both for the space and for the null terminator). Then, callstrcpy
to copy the argument string into the new array, overwrite the second-to-last index with a space and put a null terminator into the last index.