Examples
Command Line arguments
#include <stdio.h> #include <stdlib.h> /* This shows how args can be read from the Unix command line */ int main(int argc, char *argv[]){ int i; printf("The %d arguments are\n", argc); for (i=0; i<argc; i++) printf("%d %s\n",i, argv[i]); exit (0); }
Using qsort, random numbers and the clock
#include <stdio.h> #include <stdlib.h> #include <time.h> * compile on HPs using c89 -D_HPUX_SOURCE -o filename filename.c */ #define NUM 10 int comp(const void *a, const void *b ) { return *(int *)a - * (int *)b; } int main(int argc, char *argv[]) { int numbers[NUM]; int i; srand48((long)time(NULL)); printf("\nUnsorted numbers are:-\n"); for (i=0; i< NUM; i++){ numbers[i]= 1000 * drand48(); printf("%d: %3d\n", i, numbers[i]); } /* See the qsort man page for an explanation of the following */ qsort((void*) numbers, (size_t) NUM, sizeof(int), comp); printf("\nSorted numbers are:-\n"); for (i=0; i< NUM; i++) printf("%d:%3d\n", i, numbers[i]); exit(0); }
Calling other programs
The commands used from the command line can be called from C.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ FILE *popen(); FILE *fp; char string[32]; /* First use the system() call. Output will go to stdout. */ system("date"); /* Now `capture' the output of date using popen() */ fp = popen("date","r"); if (fp == NULL) fprintf(stderr,"Cannot run date\n"); else{ fgets(string, 32, fp); printf("The date command returns [%s]\n", string); pclose(fp); } }
Linked Lists
The following program creates a singly linked list. Pointers are maintained to the head and tail of the list.
#include <stdio.h> typedef struct _list_item { int val; struct _list_item *next; } list_item; /* prototypes */ list_item *add_list_item(list_item *entry, int value); void print_list_items(void); list_item *head=NULL; list_item *tail=NULL; main(int argc, char *argv[]) { tail=add_list_item(tail,5); tail=add_list_item(tail,7); tail=add_list_item(tail,2); print_list_items(); } list_item *add_list_item(list_item *entry, int value) { list_item *new_list_item; new_list_item=(list_item*)malloc(sizeof(list_item)); if (entry==NULL){ head=new_list_item; printf("First list_item in list\n"); } else { entry->next = new_list_item; printf("Adding %d to list. Last value was %d \n",value,entry->val); } new_list_item->val = value; new_list_item->next = NULL; return new_list_item; } void print_list_items(void) { list_item *ptr_to_list_item; for (ptr_to_list_item= head;ptr_to_list_item!= NULL; ptr_to_list_item=ptr_to_list_item->next) { printf("Value is %d \n", ptr_to_list_item->val); } }
Using pointers instead of arrays
#include "stdio.h" char *words[]={"apple","belt","corpus","daffodil","epicycle","floppy", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "glands","handles","interfere","jumble","kick","lustiness", "mangleworsel","nefarious","oleangeous","parsimonious",NULL}; void slow(void) { int i,j,count=0; for (i=0; words[i] != NULL ; i=i+1) for (j=0; j <= strlen(words[i]) ; j=j+1) if(words[i][j] == words[i][j+1]) count= count+1; printf("count %d\n",count); } void fast(void) { register char **cpp; /* cpp is an array of pointers to chars */ register char *cp; register int count=0; for (cpp= words; *cpp ; cpp++) /* loop through words. The final NULL pointer terminates the loop */ for (cp = *cpp ; *cp ; cp++) /* loop through letters of a word. The final '\0' terminates the loop */ if(*cp == *(cp+1)) count++; printf("count %d\n",count); } /*count the number of double letters, first using arrays, then pointers */ int main(int argc, char *argv[]){ slow(); fast(); }
A data filter
The program reads from stdin an ASCII file containing values of a variable y for integral values of x running from 0 to n-1 where n is the number of values in the file. There may be several values on each line. The program outputs the x, y pairs, one pair per line, the y values scaled and translated by factors built into the main routine..
#include <stdio.h> #include <stdlib.h> int answer; float offset; float scale; char buf[BUFSIZ]; int xcoord = 0; char *cptr; int transform(int a) { return a * scale + offset + 0.5; } char* eat_space(char *cptr){ /* This while loop skips to the nonspace after spaces. If this is the end of the line, return NULL `While a space, keep going' */ while (*cptr ==' '){ if (*cptr == '\0') return NULL; else cptr++; } return cptr; } char * next_next_num(char *cptr){ /* This while loop skips to the 1st space after a number. If this is the end of the line, return NULL `While NOT a space, keep going' */ while (*cptr !=' '){ if (*cptr == '\0') return NULL; else cptr++; } /* Now move to the start of the next number */ return eat_space(cptr); } int main(int argc, char *argv[]) { offset = 2.3; scale = 7.5; while(1){ /* if we haven't reached the end of the file ...*/ if(fgets(buf, BUFSIZ,stdin)!= NULL){ /* initialise cptr to point to the first number ...*/ cptr = eat_space(buf); do{ /* convert the representation of the num into an int */ sscanf(cptr,"%d", &num); /* print x and y to stdout */ printf("%d %d\n",xcoord, tranform(num)); /* skip to the start of the next number on the line */ cptr=next_next_num(cptr); xcoord++; }while ( cptr!=NULL); } else{ exit(0); } } }
Reading Directories
#include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #define REQUEST_DIR "/" int main(int argc, char *argv[]){ FILE *fp; DIR *dirp; struct dirent *dp; struct stat buf; dirp = opendir(REQUEST_DIR); chdir(REQUEST_DIR); /* Look at each entry in turn */ while ((dp = readdir(dirp)) != NULL) { /* Now stat the file to get more information */ if (stat(dp->d_name, &buf) == -1) perror("stat\n"); if (S_ISDIR(buf.st_mode)) printf("%s is a directory\n", dp->d_name); else if (S_ISREG(buf.st_mode)) printf("%s is a regular file\n", dp->d_name); } (void) closedir(dirp); }
Calling fortan NAG library routines
#include <stdio.h> #include <stdlib.h> /* c89 -L/usr/local/lib g01aaf.c -lnag -lcl */ main(){ int i; int n, iwt, ifail; double x[10], wt[10]; double xmean, s2, s3, s4, xmin, xmax, wtsum; iwt = 0; n = 10; ifail = 0; for (i=0;i<10;i++){ wt[i]=1; x[i]= 3.5 * i; } g01aaf(&n, x, &iwt, wt, &xmean, &s2, &s3, &s4, &xmin, &xmax, &wtsum, &ifail); if (ifail == 0){ printf("Mean is %lf, Std deviation is %lf\n", xmean, s2); printf("Max is %lf, min is %lf\n", xmax, xmin); } else printf("G01AAF failed\n"); }
Queens: recursion and bit arithmetic
This program counts the number of ways that 8 queens can be placed on a chess board without any 2 of them being on the same row, column or diagonal. It was written by M. Richards at cl.cam.ac.uk
#include <stdio.h> int count; void try(int row, int ld, int rd){ if (row == 0xFF) count++; else{ int poss = 0xFF & ~(row | ld | rd); while (poss){ int p = poss& -poss; poss = poss -p; try(row+p, (ld+p)<<1, (rd+p)>>1); } } } int main(int argc, char *argv[]){ printf("Eight Queens\n"); count = 0; try(0,0,0); printf("Number of solutions is %d\n", count); exit(0); }