Getting Started on UNIX C Programming

0. Overview

The only way to attain proficiency in programming is to practise, and practise YOU MUST! This includes trying out and experimenting with the programs presented in the lectures, as well as the tutorials, and programming exercises. It is not good enough just to read C code. You must type it in, compile it, and run it! Your programming aptitude can only be improved with programming experience. As you will be using a UNIX platform for C programming, we have provided a step-by-step walkthrough which will guide you through the following:

  1. Software Installation
  2. Basic UNIX Commands
  3. C Program Development
You need to be very familiar with programming on a UNIX platform as you will be required to program in UNIX during your weekly lab sessions.

1. Software Installation

In order to use a Unix environment in Windows, we shall use a portable version of Cygwin which is a UNIX-like environment and command-line interface. Cygwin can be installed on a portable USB thumb-drive or external hard-disk so that you can plug-and-play on any machine to do your work. We suggest a minimum disk space of 512MB for the installation. Cygwin need not be the sole application on your storage device, so you can install together with your favourite media files on your media players, provided that these are visible as removable storage devices on the machines to which they are plugged in.

You will be required to bring this external device along for your weekly lab sessions.

The detailed setup instructions for Windows and Mac machines are given below. Linux/FreeBSD users should be competent enough to perform the proper set up; just take the Mac instructions as a guide.

Download cygwin.zip and extract the contents onto your portable drive or hard-disk. You are advised to extract to the root directory of a drive (e.g. D:\, E:\, F:\, G:\). Navigate to your drive and/or folder where the files were extracted, and you will see three files.

cygwin
This folder contains all the necessary files. In particular, this folder contains another folder "home". This is your home directory in which you will save all your work. A directory is similar to a folder in Windows.
cygwin.bat (for Windows)
If you are using a Microsoft Windows machine, double click on this file to start Cygwin. Note that, by default, Windows hide known extensions. So you might only see the filename as "cygwin". However, if you check its "Type", it should be a "Windows Batch File". Do not mix this up with the other "cygwin" file, which is a type of "Windows COMMAND" file. If everything goes well, you will see a similar Cygwin interactive window as shown below.

cygwin.command (for Mac)
For a Mac, we do not rely on the UNIX functionality of Cygwin. In fact, the Mac is already based on BSD UNIX. You need to first start up the Terminal application from Finder/Applications/Utilities.

Next, check if the "gcc" C program compiler exists by entering the command "gcc --version". If a "command not found" message is output, then you will need to install Xcode. You can install Xcode either directly from the Installation DVD that comes with your Mac, or you can create an online Apple Developer Connection (ADC) account from http://developer.apple.com/mac/. Once your ADC account is created, you may login, then download and install Xcode. You will see a similar Terminal session as shown below.

Instead of double clicking "cygwin.command", you can enter the command (with its associated path) directly from within the usual Terminal session. The correct command to enter is shown when you performed the double click earlier. From the preceding example, notice that the command is "/Volumes/SOC\ CYGWIN/cygwin.command".

Whichever method you use, as long as you see the local UNIX prompt of the form "user@machine:~[xxx]$" , then you would have successfully performed the necessary setup on your local machine.

Note that user and machine varies with different users and machines, and xxx is a running number. You are now at the home directory level of your very own UNIX platform. All the common UNIX commands can now be used. To exit, do not close the window by clicking on × at the top corner. Just enter the command "exit". You may also open multiple windows, if necessary, by repeatedly clicking on "cygwin.bat" or "cygwin.command".

2. Basic UNIX Commands

Now is the time to start your UNIX adventure. The power of UNIX stems from the many commands it offers. The following are a few commonly used commands. This list is by no means exhaustive and you are urged to explore on your own. Note that UNIX commands are case-sensitive.

In the examples below, bold words are commands which you are expected to enter. All commands are to be entered after the UNIX (local or sunfire) prompt of the form

user@machine:~[xxx]$
~ indicates that you are currently in your home directory.

a. Directory commands

pwd to Print current Working Directory to show you which directory you are currently in
 
user@machine:~[xxx]$ pwd
/home
ls to LiSt files in your current directory
 
user@machine:~[xxx]$ ls
c     doc
  You may also use "ls -F" for more information (-F is one of the many options/flags available for the ls command. To see a complete list of the options, refer to the man pages, ie. "man ls".)
 
user@machine:~[xxx]$ ls -F
c/       doc/
  The slash (/) beside the filename tells you that the file is a directory (folder). A normal file does not have a slash (/) beside its name when "ls -F" is used.
  You may also use the "ls -l" command (dash L) to display almost all the file information, include the size of the file and the date of modification. Try it now!
cd to Change Directory from current directory to another
 
user@machine:~[xxx]$ cd c

user@machine:~/c[xxx]$ ls -F
ch1_1.c   ch2_1.c   ch2_2.c   ch2_3.c   ch2_4.c
  Note that the prompt changes to ~/c to indicate that you are now in the c directory below your HOME directory.
Entering "cd" alone brings you back to your HOME directory, ie. the directory in which you started with when you first logged into the system.
 
user@machine:~/c[xxx]$ cd

user@machine:~[xxx]$
mkdir to MaKe a subDIRectory in current directory
 
user@machine:~[xxx]$ mkdir another

user@machine:~[xxx]$ ls -F
another/   c/     doc/
rmdir to ReMove a subDIRectory in current directory -- note that a directory must be empty before it can be removed.
 
user@machine:~[xxx]$ rmdir another

user@machine:~[xxx]$ ls -F
c/     doc/

b. File commands

cp to CoPy files
 
user@machine:~[xxx]$ cd doc

user@machine:~/doc[xxx]$ cp abridged.txt anotherfile

user@machine:~/doc[xxx]$ ls
abridged.txt   anotherfile    faq.txt        tutor
mv to MoVe files from one directory to another; can also be used to rename files.
 
user@machine:~/doc[xxx]$ mv anotherfile afile

user@machine:~/doc[xxx]$ ls
abridged.txt   afile          faq.txt        tutor
rm to ReMove files. Be careful with this command -- files deleted cannot be restored (unless they have been backed up during the normal backup cycle).
 
user@machine:~/doc[xxx]$ rm afile
rm: remove regular file `afile'? y

user@machine:~/doc[xxx]$ ls
abridged.txt   faq.txt        tutor

c. Command to display text files

cat to string together or display (CATenate) the contents of files onto the screen
 
user@machine:~/doc[xxx]$ cat abridged.txt
less variant of "cat" (includes features to read each page leisurely)
 
user@machine:~/doc[xxx]$ less abridged.txt
  In "less", use <space> to move down one page, 'b' to move Back up one page, and 'q' to Quit from "less".


An online help facility is available in UNIX via the "man" command ("man" stands for MANual). To look for more information about any UNIX command, for example, "ls", type "man ls". Type "man man" to find out more about the man facility. To exit "man", press "q".

3. C Program Development

The process of creating a working C program involves the following steps:

        +---------+
+---+-->|  EDIT   |
|   ^   +---------+
|   |        |
|   |        |
|   |        v
|   |   +---------+
|   +---| COMPILE |
|       +---------+
|            |
|            |
|            v
|       +---------+
+-------|   RUN   |
        +---------+
  1. Using an editor, type in the source code (filename must have extension .c, eg: ch1_1.c)
  1. Compile your program to obtain the executable file. If there are compilation errors, identify them and re-edit the source code before you proceed.
  1. Run your executable file by typing the name of the executable file.
    If there are run-time errors, you must identify them and re-edit the source code, and compile again.

3.1 A sample C program

Three sample C programs have been copied into your "c" subdirectory. Use "cat" or "less" to view the program "ch1_1.c".

user@machine:~/doc[xxx]$ cd

user@machine:~[xxx]$ cd c

user@machine:~/c[xxx]$ less ch1_1.c
/*---------------------------------------------------*/
/*  Program chapter1_1                               */
/*                                                   */
/*  This program computes the                        */
/*  distance between two points.                     */

#include <stdio.h>
#include <math.h>

int main(void)
{
    /*  Declare and initialize variables.  */
    double x1=1, y1=5, x2=4, y2=7,
        side_1, side_2, distance;

    /*  Compute sides of a right triangle.  */
    side_1 = x2 - x1;
    side_2 = y2 - y1;
    distance = sqrt(side_1*side_1 + side_2*side_2);

    /*  Print distance.  */
    printf("The distance between the two points is "
           "%5.2f \n",distance);

    /*  Exit program.  */
    return 0;
}
/*---------------------------------------------------*/

Compile and run the program as follows (use the "gcc" compiler):

user@machine:~/c[xxx]$ gcc -Wall -lm ch1_1.c

This will compile "ch1_1.c" and produce the executable file "a.exe" (on a Mac or any UNIX-based machine it generates "a.out") . Note that the "-lm" flag (dash L M) is used whenever a C program contains the line #include <math.h>. The "-Wall" flag tells the compiler to generate all warnings. Note that the W in "-Wall" must be an uppercase letter. C is case-sensitive.

If gcc compiles your program successfully, you will see no output. With gcc, "no news is good news". You are now ready to execute your program by typing the name of the executable:

user@machine:~/c[xxx]$ ./a.exe

This will execute the file "a.exe". Note that we prefix it with "./" to indicate that "a.exe" is in the current directory. For a Mac or Unix-based machine, you should execute "a.exe" accordingly.

3.2 Create your first C program "first.c"

You need an editor to write your programs. In this course, you shall be using Vim -- a powerful editor with many commands, but even with the knowledge of a few simple commands it is quite easy to use and very powerful.

Get into your c subdirectory if you are not there. Enter "vim first.c", then press the "i" key. You will see that the words "-- INSERT --" appear on the bottom left corner of your screen. You are now in INSERT mode. While you are in INSERT mode, you may use the arrow keys (Up, Down, Left, Right) to move around your program, as well as the Backspace key and Delete key to delete text. The PageUp and PageDown keys do not work, so do not use them. Do not use the scroll bar as it does not always work as expected.

Notice that line numbers (1, 2, 3, etc.) are displayed on the left. This helps you to easily identify a number by its line. Line numbers are NOT part of C code. This is extremely useful when identifying the location of compilation errors.

Type in the following program:

#include <stdio.h>

int main(void)
{
    int a=27, b=6, c;

    c = a%b;
    printf("The value of c is %i.\n", c);

    return 0;
} 

Note that for simplicity, the above program has no documentation. A good program should include documentation, at least the identity of the author, the purpose of the program and other relevant information. Keep this in mind when you write your own programs.

When you are done, press "<ESC>:wq<ENTER>" (more clearly seen as pressing the following four keys one after another: <ESC> : w q <ENTER>) to save your program and exit from the Vim editor. <ESC> means press the Escape key, then press the colon key (shift-;), then press w (the w is a lowercase w), then press q, and finally <ENTER> means press the Enter key.

If you want to save your file without exiting from the Vim editor, press "<ESC>:w<ENTER>". It is a good habit to save your file periodically so that if the network or the system goes down for any reason, you will not lose your hard work.

When you startup Vim, it begins in COMMAND mode. One way to go into INSERT mode is to press the "i" key. While in INSERT mode, you can type in your C code. To switch back to COMMAND mode, press the "<ESC>" key.

The following shows you a list of useful commands in Vim:

When you begin writing bigger programs, you will find the need to move around or delete portions of code. To do this in Vim, ensure that you are in COMMAND mode by pressing <ESC>. Using your arrow keys, go to the top (or bottom) of the section of code you want to move, press uppercase "V "to start highlighting. Using your up/down arrow keys, highlight the entire section of code.

Depending on what you want to do to the highlighted sections, you may press "d" for delete, "x" for cut or "y" for copy (or yank). Once a section has been cut or yanked, you may move to the appropriate point in your code and press uppercase "P" to paste.

You may also choose to use your mouse to highlight blocks of text and use the native Window's cut-and-paste functionality, but bear in mind that the end effect may be less desirable. In UNIX, we never use the mouse.

To undo or redo in Vim, ensure that you are in COMMAND mode and press lowercase "u" or control-R respectively. If you would like to learn more about Vim commands, click HERE. Another useful reference can be found HERE.

3.3 Compile and run your program

Having "edited" your program, save your work and exit Vim. Compile your program by entering the following command:
user@machine:~/c[xxx]$ gcc -Wall first.c

There will be error messages if your program has errors. Go to Step 3.2 to make the necessary corrections and re-compile. If there are no compilation errors, proceed with program execution as follows:

user@machine:~/c[xxx]$ ./a.exe

Note that this "a.exe" (or "a.out" in Mac or Unix machine) file is the executable version of "first.c", and it has replaced the earlier "a.exe" file which is the executable file of "ch1_1.c", since there must not be two files with the same name in a directory. To avoid this, you may specify the name of the executable file, instead of leaving it to the system to use the default name "a.exe". The trick lies in the "-o" option of the "gcc" command:

user@machine:~/c[xxx]$ gcc -Wall first.c -o first.exe

In the above example, the executable file for "first.c" will be called "first.exe". Note that the name of the executable file MUST IMMEDIATELY follow the -o. Be careful of this or you may lose your source file!

Do NOT ever type the following:

user@machine:~/c[xxx]$ gcc -Wall first.c -o first.c

What is wrong with the above statement? It states that you want to output the executable file to first.c. This is wrong, because the executable file should NOT be the same as your source program file. If you type the command wrongly, you will LOSE YOUR SOURCE FILE, and you would have to start typing your source file all over again, wasting your time and your effort. So be careful in what you type.

3.4 Another program

Use the instructions in Steps 3.2 and 3.3 to create, compile and run the following program "second.c". What is the output of the program? How could you add a blank line before and after the line of output, to make it into a 3-line output?

#include <stdio.h>

int main(void)
{
    double a;
    double b=6, c=18.6;

    a = b/c;
    printf("b is %3.1f, c is %3.1f. ", b, c);
    printf("a is %.6f.\n", a);

    return 0;
}

Experiment a little by changing the "3.1" and ".6" to some other values and try to figure out what they do. Try also to combine the two printf statements into one. Programming is fun in that you can try out all sorts of things and see the end results yourself! A lot can be learned through self-exploration alone and you needn't worry about setting sunfire on fire!

3.5 A program with errors

The program "third.c" below contains syntax errors which will be reported during compilation. Though you may be new to C, the error messages do give some information, and by referring to the few correct sample programs above, you should be able to spot some, if not all, of the errors.

*/ This program contains MANY syntax errors /*
include (stdio.h);

int main(void)
{
    double num

    num := 305.68;
    printf("num is ")
    printf('%6.1f\n', Num);

    return 0;
}

Edit the program edit to correct the errors. Compile it. If there are still errors, what must you do? Yes, edit the program again, and re-compile. Assuming that all errors have been corrected, what is the output of this program?


Appendix A: Pre-loaded files

These are the files copied into your home directories by the setup program in sunfire, or preloaded in the cygwin/home folder.

In your "c" subdirectory:

  1. ch1_1.c: Computes the distance between two points.
  2. ch2_1.c: Prints two values as characters and integers.
  3. ch2_2.c: Uses linear interpolation to compute the freezing temperature of seawater.
  4. ch2_3.c: Estimates new velocity and acceleration values for a specified time.
  5. ch2_4.c: Prints the system limitations.

In your "doc" subdirectory:

  1. abridged.txt: Answers (abridged) to the C FAQ (Frequently Asked Questions).
  2. faq.txt: Answers (complete) to the C FAQ.
  3. tutor: The Vim tutor.

Appendix B: Restoring your home directory

If for some reason you need to restore the original contents of your home directory, you will need to perform the following.

user@machine:...[xxx]$ cd
user@machine:~[xxx]$ setup

You will be asked to confirm the restoration.

user@machine:~[xxx]$ source .bash_profile

The contents of the c and doc directories, as well as other configuration files will be restored back to normal.