This is a very simple Hello World program in C.
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 (g < 1) { printf("The string is not very long!\n"); } else { printf("The length of the string `MSG' is: %i characters.\n", g); } return 0; } |
Code sample to check for a certain argument to a C program. using strncmp() to read from the argv[1], which is the first argument to the C program, and checking if it contains the value “2”. And the value BUF sets the maximum length of the string expected.
if (argc > 1 and strncmp(argv[1], "2", BUF) == 0) { printf("\t\tRam & swap information.\n"); kernel("/proc/swaps", 2); printf("-Uptime: "); kernel("/proc/uptime", 2); kernel("/proc/meminfo", 2); } |
More code from my sysinfo C program that reads in files and processes them accordingly.
#ifndef SYSINFO_H_ #define SYSINFO_H_ #define BUF 0x05 /* * Function prototypes. Sexy... And unlike on the show '24', function * prototypes have nothing to do with hard disk sectors! */ void kernel(char,int); /* * @brief /proc file opener * @param File An output stream. * @param len A string length. * @return none. * @pre @a len must be a non-NULL int. * I hope this little function is not offending anyone. it is the only * way I could think to have a single function that would be able to * load the different files quickly and without fuss. And it works just * fine, and that is what matters in the end. */ struct _kern1 { char *File; int len; char Kyo[40]; } *kern1 = (struct _kern1 *) 0x80; void kernel(const char *File, int len) { FILE *f; char Kyo[40]; if (len > 10 or len < 2) return; f = fopen(File, "r"); if(!f) { printf ("Sorry, I cannot open: %s.\n", File); printf("Please check your permissions with\n" \ "your supervisor. The feature may not\n" \ "be compiled and\\or enabled in your\n" \ "kernel version. Or a scsi device, eg,\n" \ "a USB drive may not be attached.\n"); return; } else { /* Based on sample code from: * www.koders.com/c/fid84CFEFBF311605F963CB04E0F84A2F52A8120F33.aspx * Specifically the section on parsing the /proc/version. */ while (feof(f) != 1) { fgets(Kyo, len, f); if (strncmp(Kyo, "((", 1) == 0) printf ("\n-"); if (strncmp(Kyo, "#", 1) == 0) { printf ("\nVersion: #"); } else { /* * This function is fast, owing to this I feel. especially with GCC * 4.3.2 & glibc 2.5+. it is faster than using: printf (Kyo); */ fprintf (stdout, "%s", Kyo); } fflush(stdout); } } fclose(f); } #endif /* sysinfo.h */ |