Miscellaneous programming tricks with C.

Posted: May 3, 2012. At: 2:48 PM. This was 5 years ago. Post ID: 3667

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 &lt; 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 &gt; 1 and strncmp(argv[1], "2", BUF) == 0) {
	printf("\t\tRam &amp; 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 to 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 &gt; 10 or len &lt; 2)
	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");
	} 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 &amp; glibc 2.5+. it is faster than using: printf (Kyo);
				fprintf (stdout, "%s", Kyo);
#endif /* sysinfo.h */

No comments have been made. Use this form to start the conversation :)

Leave a Reply