Example C Programs
I've written a bunch of short C programs to demonstrate how C programs
interface with and use the Unix operating system. Here are links to
them, in approximately the order in which I'll discuss them:
- ask_examples.tar, an archived directory
containing four files:
An example of writing C code spread over several source files.
- oct8_1.c, which prints out the word "Hello"
followed by its command-line arguments.
- cswap.c, which does the same job as the shell
script swap: it takes two
command-line arguments and prints them in reverse order.
- mycat.c, which does the same job as the "cat"
command, at least in a simple form: with no arguments, it copies stdin
to stdout, and with one argument, it copies the specified file to
- linkedlist.c and node.h, examples of memory allocation and structs in
- mycat2.c, a more general version that allows
more than one file. It's also restructured to use a "dumpfile" function
rather than doing the copying in-line.
- evalenv.c, which takes the name of an
environment variable and prints out its value, if any.
- myset.c, which sets the value of an
environment variable. Not a particularly useful program, since
environment variables changed in a subprocess don't affect their values
in the parent process.
- wsp.buggy.c. Several years ago I
assigned people to write a program which would take an environment
variable name and a filename, evaluate the environment variable as a
colon-delimited list of directories (like PATH), and look for the
specified filename in each of those directories. (The complete
assignment is here.)
This is a
BUGGY version of that program; I intentionally
introduced some bugs to give people practice using gdb.
- buggy_pets.zip, another example of
a C program with bugs in it, to give people practice using gdb.
- clongword.c, which finds the longest word
- clongword2.c, which also finds the longest
word in stdin, but it uses scanf rather than reading character by
- clongword3.c, which does the exact same
thing, but is a little more "bulletproof" in that it refuses to read a
longer word than it has space for. Demonstrates use of
Several examples using the
fork system call to spawn a subprocess. The whole
directory is downloadable here.
Makefile, an example of
input for compiling a bunch of different C programs.
(Note that it uses
Wed Oct 3 10:30:03 EDT 2007
Stephen Bloch / email@example.com