I want to create an overlay in terminal
This Q&D shows the time in right/bottom
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <termios.h>
#include <error.h>
#include <unistd.h>
#include <time.h>
static char termbuf[2048];
int main()
{
char *termtype = getenv("TERM");
time_t timer;
char buffer[26];
struct tm* tm_info;
if (tgetent(termbuf, termtype) < 0) {
error(EXIT_FAILURE, 0, "Could not access the termcap data base.\n");
return 1;
}
int lines = tgetnum("li");
int columns = tgetnum("co");
int pos=1;
while (1) {
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
printf("\033[s");
fflush(stdout);
printf("\033[%d;%dH%s\n", lines - 2, columns - 20, buffer);
printf("\033[u");
sleep(1);
}
return 0;
}
it is compiled with:
$ gcc time-overlay.c -ltermcap -o time-overlay
And to use it:
$ ./time-overlay &
It will show:
2017-04-29 12:29:15
And keep updating time.
To stop:
$ fg
Ctrl+C
But, is there a better way to do that with some library that abstracts low level calls (like save restore cursor position or print in some line/col)
I want to keep existing terminal output (so curses with initscr() will not work)
This is how you would use termcap (or anything provides a termcap interface, e.g., ncurses):
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#define MAXTERM 2048
#define EndOf(s) (s) + strlen(s)
int
main(void)
{
char termbuf[MAXTERM];
char workbuf[MAXTERM];
char *working = workbuf;
int lines, columns;
char *save_cursor, *move_cursor, *restore_cursor;
if (tgetent(termbuf, getenv("TERM")) < 0) {
fprintf(stderr, "Could not access the termcap database.\n");
return EXIT_FAILURE;
}
lines = tgetnum("li");
columns = tgetnum("co");
save_cursor = tgetstr("sc", &working);
move_cursor = tgetstr("cm", &working);
restore_cursor = tgetstr("rc", &working);
while (1) {
time_t timer;
char buffer[1024];
struct tm *tm_info;
time(&timer);
tm_info = localtime(&timer);
strcpy(buffer, save_cursor);
sprintf(EndOf(buffer), tgoto(move_cursor, columns - 20, lines - 2));
strftime(EndOf(buffer), 26, "%Y-%m-%d %H:%M:%S", tm_info);
strcat(buffer, restore_cursor);
write(fileno(stderr), buffer, strlen(buffer));
sleep(1);
}
return EXIT_SUCCESS;
}
It could still be improved since the various strings returned from tgetstr are not guaranteed to be provided by all terminal descriptions, and of course, termcap applications always have buffer-overflow issues to work around.
Related
I am using libwireshark.so, libwsutil.so and libwiretap.so in order to make program which decodes packets like Wireshark in C on Ubuntu Linux.
I am try to run function named epan_init() from libwireshark.so but I get the following run-time error:
Enter file name: 1.pcap
Enter print type(0-XML, 1-TEXT): 1
Init function start
Segmentaion fault (core dumped)
Process returned 139 (0x8B) execution time : 2.882 s
Press ENTER to continue.
SOURCE CODE:
#define HAVE_STDARG_H 1
#define WS_MSVC_NORETURN
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <wireshark/epan/epan.h>
#include <wireshark/epan/print.h>
#include <wireshark/epan/timestamp.h>
#include <wireshark/epan/prefs.h>
#include <wireshark/epan/column.h>
#include <wireshark/epan/epan-int.h>
#include <wireshark/wsutil/privileges.h>
#include <wireshark/epan/epan_dissect.h>
#include <wireshark/epan/proto.h>
#include <wireshark/epan/ftypes/ftypes.h>
#include <wireshark/epan/asm_utils.h>
///Prototypes
void getString(char *msg, char **input);
int init(char *filename);
///Print type of packets
typedef enum {PRINT_XML, PRINT_TEXT} print_type_t;
capture_file cfile;
int main()
{
///Variables
int err;
char *filename = NULL;
print_type_t print_type = PRINT_XML;
getString("Enter file name: ", &filename);
printf("Enter print type(0-XML, 1-TEXT): ");
scanf("%d",&print_type);
err = init(filename);
if(err)
{
printf("Main function(): Error init");
return 1;
}
printf("\n\n\n%s\n\n\n",cfile.filename);
//printf("Hello World");
return 0;
}
///Get input from user
void getString(char *msg, char **input)
{
char buffer[100];
printf("%s", msg);
fgets(buffer, sizeof(buffer), stdin);
*input = calloc(sizeof(char), strlen(buffer) + 1);
strncpy(*input, buffer, strlen(buffer));
}
///
int init(char *filename)
{
printf("Init function start\n");
int err = 0;
gchar *err_info = NULL;
e_prefs *prefs_p;
/// Called when the program starts, to enable security features and save whatever credential information we’ll need later.
init_process_policies();
printf("Init proccesss politices done");
/// Init the whole epan module. Must be called only once in a program. Returns TRUE on success, FALSE on failure.
epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL);
//printf("epan init done");
cap_file_init(&cfile);
cfile.filename = filename;
return 0;
}
void cap_file_init(capture_file *cf)
{
/* Initialize the capture file struct */
memset(cf, 0, sizeof(capture_file));
cf->snap = WTAP_MAX_PACKET_SIZE;
}
how to get minute of the system time from C program? can I use gettimeoftheday?? If anyone has C program which can do this please share, I'm a newbie.Thanks
some sample code
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
return 0;
}
You can use strftime to get only the minutes part :
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[0x100];
time_t curtime;
// Don't forget to check the return value !
curtime = time(NULL);
if (curtime == -1)
{
perror("time()");
return 1;
}
strftime(buffer,0x100,"%M",localtime(&curtime));
printf("minutes: %s\n", buffer);
return 0;
}
No need to use gettimeofday here, use it only if you want a precision better than seconds.
#include <stdio.h>
#include <time.h>
int main()
{
time_t curtime;
char buffer[30];
struct tm* tm_info;
time(&curtime);
tm_info = localtime(&curtime);
strftime(buffer, 30, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
return 0;
}
%Y:- will print year
%m:- will print Month
%d:- will print day
%H:- will print Hour
%M:- will print Minute
%S:- will print Second
If I send the following string to the rpi via serial comms
echo "#q10" > /dev/ttyUSB0
Edit:
This is the app output from the raspberry pi (The linefeed character ^M seems to be the problem)
I have tried different length strings that also give inconsistencies
The code is as follows. I am using the serial wiring library from
Gordons project
#include <stdio.h>
#include <wiringSerial.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
int fd;
struct obj_Properties
{
char *one;
char *two;
char *three;
char *four;
};
int main()
{
if ((fd = serialOpen("/dev/ttyUSB0", 9600)) < 0)
{
return 1;
}
for(;;){
while (serialDataAvail (fd))
{
struct obj_Properties prop;
prop.one = serialGetchar(fd);
prop.two = serialGetchar(fd);
prop.three = serialGetchar(fd);
prop.four = serialGetchar(fd);
printf ("%c %c %c %c\n", prop.one, prop.two, prop.three, prop.four);
fflush (stdout) ;
}
usleep(10000);
}
}
I am trying to make a clock in C, but the screen is not properly clearing, it just keeps printing to a new line. How am I improperly using fflush?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
while (1) {
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("%s", asctime (timeinfo));
fflush(stdout);
}
return 0;
}
This strips out the newline from the asctime string and then uses a return to push the cursor back to the start of line
#include <string.h>
int main()
{
while (1) {
time_t rawtime;
char st[30];
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
sprintf (st,"%s", asctime (timeinfo));
*(index(st,'\n'))='\0';
printf("\r%s",st);
flush(stdout);
sleep(1);
}
return 0;
}
This one has the advantage that it will work from the current location on the screen, no matter what that is. I added a label to print "The time is: " in order to show this. It does this by back spacing from the end of the time string rather than going to an absolute screen position or column. Caveat: The hack to get sleep() under Visual C has not been tried.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#ifdef _MSC_VER
#include <windows.h>
#define sleep(T) Sleep((T) * 1000)
#else
#include <unistd.h>
#endif
int main(void)
{
char buf[42];
time_t the_time[1];
int i, len;
printf("The time is: ");
for (;;) {
time(the_time);
len = strlen(strcpy(buf, asctime(localtime(the_time)))) - 1;
printf("%.*s", len, buf);
for (i = 0; i < len; i++) putchar('\b');
fflush(stdout);
sleep(1);
}
return 0;
}
This will do it... (uses an evil windows call SetConsoleCursorPosition(), but does the trick)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gotoxy(int x, int y);
int main()
{
while (1) {
time_t rawtime;
struct tm * timeinfo;
gotoxy(0,0);//set to the upper left hand corner
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("%s", asctime (timeinfo));
fflush(stdout);
}
return 0;
}
void gotoxy(int x, int y)
{
COORD pos = {x, y};
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, pos);
}
Try this for POSIX:
#!/usr/bin/tcc -run
#include <stdio.h>
#include <termios.h>
int main ()
{
struct termios ts0, ts1;
char cls [FILENAME_MAX];
FILE *f;
f = popen ("tput clear", "r");
fgets (cls, FILENAME_MAX, f);
pclose (f);
tcgetattr (0, &ts0);
ts1 = ts0;
ts1.c_lflag &= ~ECHO;
ts1.c_lflag &= ~ICANON;
tcsetattr (0, TCSAFLUSH, &ts1);
fputs (cls, stdout);
while (1) putchar (getchar ());
tcsetattr (0, TCSAFLUSH, &ts0);
return 0;
}
need some advice on this one as im struggling abit and cannot figure it out.
i have a file that gets updated on a PC to indicate a system ran and what time it ran. i am writing a very simple linux console app (will eventually be a nagios plugin). that reads this file and responds depending on what it found within the file.
i am a total newbie to programming on Linux and using C so please be patient and if you would explain any answers it would really be appreciated.
basically i want to convert a char array containing 5 characters into an integer, however the 5th char in the array is always a letter. so technically all i want to-do is convert the first 4 chars in the array to a integer... how?? ive tried multiple ways with no success, my problem is that presently i do not have a good grasp of the language so have no real ideas on what it can and cannot do.
here is the source to my program.
basically the buf array will be holding a string taken from the file that will look something like this
3455Y (the number will be random but always 4 chars long).
Sorry for the poor formatting of the code, but i cannot get this stupid window for love nor money to format it correctly....
include <fcntl.h>
include <unistd.h>
include <stdio.h>
include <stdlib.h>
include <time.h>
include <string.h>
define COPYMODE 0644
int main(int argc, char *argv[])
{
int i, nRead, fd;
int source;
int STATE_OK = 0;
int STATE_WARNING = 1;
int STATE_CRITICAL = 2;
int STATE_UNKNOWN = 3;
int system_paused = 0;
char buf[5];
int testnumber;
if((fd = open(argv[1], O_RDONLY)) == -1)
{
printf("failed open : %s", argv[1]);
return STATE_UNKNOWN;
}
else
{
nRead = read(fd, buf, 5);
}
close(source);
if (buf[4] == 'P')
{
printf("Software Paused");
return STATE_WARNING;
}
else
{
return STATE_OK;
}
time_t ltime; /* calendar time */
struct tm *Tm;
ltime=time(NULL); /* get current cal time */
Tm=localtime(<ime);
int test;
test = Tm->tm_hour + Tm->tm_min;
printf("%d", test);
printf("%d", strtoi(buf));
}
You can use sscanf to do the job:
int num = 0;
sscanf(buf, "%4d", &num);
Then num should hold the number from the line in the file.
You can use atoi
atoi requires one char * argument and returns an int.
If the string is empty, or first character isn't a number or a minus sign, then atoi returns 0.If atoi encounters a non-number character, it returns the number formed up until that point
int num = atoi(buf);
if you want to convert the first four characters of a string to an integer do this:
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
uint8_t convertFirstFourChars(char * str, uint32_t *value){
char tmp[5] = {0};
strncpy((char *) tmp, str, 4);
*value = strtoul(tmp);
return errno;
}
then call / test this function like this
#include <stdint.h>
#include <stdio.h>
int main(int argc, char **argv){
char test1[5] = "1234A";
char test2[5] = "ABCDE";
uint32_t val = 0;
if(convertFirstFourChars((char *) test1, &val) == 0){
printf("conversion of %s succeeded, value = %ld\n", test1, val);
}
else{
printf("conversion of %s failed!\n", test1);
}
if(convertFirstFourChars((char *) test2, &val) == 0){
printf("conversion succeeded of %s, value = %ld\n", test2, val);
}
else{
printf("conversion of %s failed!\n", test2);
}
return 0;
}
FWIW, don't use atoi(...) because it converts any string to an integer regardless of its validity as a number. atoi("foo") === 0.
this is as much of your code as I was able to recover from the formatting:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#define COPYMODE 0644
int main(int argc, char *argv[])
{
int i, nRead, fd;
int source;
int STATE_OK = 0;
int STATE_WARNING = 1;
int STATE_CRITICAL = 2;
int STATE_UNKNOWN = 3;
int system_paused = 0;
char buf[5];
int testnumber;
if((fd = open(argv[1], O_RDONLY)) == -1)
{
printf("failed open : %s", argv[1]);
return STATE_UNKNOWN;
}
else
{
nRead = read(fd, buf, 5);
}
close(source);
if (buf[4] == 'P')
{
printf("Software Paused");
return STATE_WARNING;
} else {
return STATE_OK;
}
time_t ltime; /* calendar time /
struct tm Tm;
ltime=time(NULL); / get current cal time */
Tm=localtime(<ime);
int test;
test = Tm->tm_hour + Tm->tm_min;
printf("%d", test);
printf("%d", strtoi(buf));
}
this is the version that does what you specified:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#define COPYMODE 0644
int main(int argc, char *argv[])
{
int i, nRead, fd;
int source;
int STATE_OK = 0;
int STATE_WARNING = 1;
int STATE_CRITICAL = 2;
int STATE_UNKNOWN = 3;
int system_paused = 0;
char buf[5];
int testnumber;
if((fd = open(argv[1], O_RDONLY)) == -1)
{
printf("failed open : %s", argv[1]);
return STATE_UNKNOWN;
}
else
{
nRead = read(fd, buf, 5);
}
close(source);
if (buf[4] == 'P')
{
printf("Software Paused");
return STATE_WARNING;
}/* else {
return STATE_OK;
buf[4] = 0;
} */
time_t ltime; /* calendar time */
struct tm *Tm;
ltime=time(NULL); /* get current cal time */
Tm=localtime(<ime);
int test;
test = Tm->tm_hour + Tm->tm_min;
printf("%d\n", test);
printf("%d\n", atoi(buf));
}
The biggest problem with your code was the if statement with the returns in each branch, insuring that nothing after the if statement was ever executed.