How to test if a C program on Linux is running from a TTY or not.

This simple C program will test whether it is running from a TTY or not. This is a simple test, but it could be quite useful. #include <stdio.h> #include <poll.h> #include <unistd.h>   int main(int argc, char* argv[]){   struct pollfd fds[1] = {{.fd = STDIN_FILENO, .events = POLLIN}};   if (!poll(fds, sizeof(fds) / sizeof(struct … Read more

Miscellaneous programming tricks with C.

This is a very simple Hello World program in C. int main() { write(1, "Hello World\n", 14); }int main() { write(1, "Hello World\n", 14); } Counting how long a text string is. #include <stdio.h> #include <string.h> #define MSG "Hello Doctor, let’s get back to the TARDIS!" int main() { int g; g = strlen(MSG); if … Read more

Very nice C code to generate a random string. And some other useful info.

This code generates a random string when run, this could be quite useful. Print some very useful Linux system information using C. These two C programming samples should be quite useful to any programmer on Linux. Print a random fortune from an array. This program prints a random fortune from an array. This is a … Read more

Very useful C program. Print a random fortune.

Here is one of my programs. I wrote this ages ago and it uses the standard ASCII character set. This will print a random fortune by running the fortune app to get a fortune and this selects a category to print from. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <string.h> const char* x[] … Read more

Return the length of a string easily in C.

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; }#include <stdio.h> #include <stdlib.h> int main (void) { char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int len_str; … Read more

Very useful C code samples. These might be very useful to someone.

Some very useful code samples for any C programmer. These might give you some new ideas. Print the time and date with C. #include <time.h> // For time function (random seed). #include <stdio.h> // For extra functions. printf(). #include <stdlib.h> // For getenv();   #define format "The time and date is: %A %d %B %Y. … Read more

How to write a Hello World program in C that does not use main().

This simple program is a Hello World example that does not use the main() function. This is certainly possible in a C program. #define syscall(a, D, S, d) __asm__ __volatile__("syscall" : : "a"(a), "D"(D), "S"(S), "d"(d))   void _start(void) { syscall(1, 1, "Hello, World\n", 14); syscall(60, 0, 0, 0); }#define syscall(a, D, S, d) __asm__ … Read more