This simple code will return the length of a string easily.
#include <stdio.h> #include <stdlib.h> int main (void) { char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int len_str; // calculates length of string len_str = sizeof(base64) / sizeof(base64[0]); printf("%d\n", len_str); return 0; } |
This could be a very useful tip for a programmer.
Do something if the program is run with the 5 parameter, e.g ./myprog 5
.
if (argc > 1 and strncmp(argv[1], "3", BUF) == 0) { printf("\t\tCdrom drive information.\n"); // kernel("/proc/sys/dev/cdrom/info", 5); strncpy(Args, "/proc/sys/dev/cdrom/info", 24); sprintf(buf, "cat %s\n", Args); fflush(stdout); system(buf); } |
A good way to check if the program was run with no parameters is this.
char* myarg1 = argv[1]; static char Args[256]; char buf[256]; if (!argc or !myarg1) { print_menu(); } |
And the print_menu function.
enum { VERSION = 160 }; #define SYSINFO "Sysinfo version v%i.%i" const char *p = "System Information Program"; char ver[128]; void print_menu() { printf("\tSysinfo. %s\n\n", p); printf("1 - Kernel Information.\n2 - Memory & processes.\n"); printf("3 - CDROM Information.\n4 - View list of sound cards.\n"); printf("5 - View Real Time Clock Information.\n"); printf("6 - View motherboard and BIOS information.\n"); printf("7 - View information about your Xorg display.\n"); printf("8 - View information about your IP addresses.\n"); sprintf (ver, SYSINFO, VERSION / 100, VERSION % 100); printf("\n%s, by John Cartwright 2007.\nsysinfo comes with ", ver); printf("ABSOLUTELY NO WARRANTY. This\n is open source software,"); printf("and you are welcome to \nredistribute it under certain "); printf("conditions as \noutlined in the GNU Public License.\n\n"); exit(0); } |
That is a great way to print a menu for your program when no parameters are issued to it.
This is a nice bit of code. It returns your screen resolution in C.
printf("\t\tXorg information.\n"); Display *display; Screen *screen; display = XOpenDisplay(NULL); int count_screens = ScreenCount(display); printf("Total count screens: %d\n", count_screens); for (int i = 0; i < count_screens; ++i) { screen = ScreenOfDisplay(display, i); printf("\tScreen %d: %dX%d\n", i + 1, screen->width, screen->height); } XCloseDisplay(display); |