CS31 Weekly Lab: Week 10

command line args, 2-D arrays, file I/O, timing

Week 10 lab topics:

  1. command line arguments and atoi function
  2. file I/O
  3. dynamically allocated 2-D arrays
  4. timing things
  5. FYI: some information on using ascii escape codes to change the color of text printed to the terminal

Create a week10 subdirectory in your weeklylab subdirectory and copy over some files:
    $ cd cs31/inclass
    $ cp -r ~mauskop/public/cs31/week10 .
    $ cd week10

The matrix.c program highlights all of this week's topics.


command line arguments and atoi function

We can define main with this signature:

int main(int argc, char *argv[]) { ... }
The first parameter to main, argc, is the number of command line arguments. For example, if the user enters:
./a.out 10 11 200
argc will be 4 (a.out counts as one of the command line arguments, and 10, 11, and 200 as three more).

Each command line argument is passed to main in the second parameter, argv, as a string (argv is an array of strings):

        -----
argv[0]:| *-|-----> "./a.out"
        -----
argv[1]:| *-|-----> "10"
        -----
argv[2]:| *-|-----> "11"
        -----
argv[3]:| *-|-----> "200"
        -----
argv[4]:| *-|-----|     (NULL pointer: no more command line strings)
        -----
C has functions that can convert strings of numeric characters to their int or float values.
int x = atoi(argv[1]);  // x gets the int value 10
See the man page for atoi for more information (man atoi).

file I/O

Here's some documentation about file I/O in C: File I/O in C

Dynamically Allocated 2-D Arrays

More information about arrays in C, including dynamically allocated 2D arrays: Arrays in C (we will use Method 1 for dynamically allocated 2D arrays).

Timing things

The gettimeofday function gives us the current time. If we save the time just before we start something and just after we end that thing, then we can subtract the start time from the stop time to get the elapsed time. This function returns the time as a struct with two fields, the time in seconds and any remainder in microseconds (millionths of a second).


Printing in color with ascii escape codes

You can use ascii escape codes to print things in color in the terminal window. The general form of an escape sequence is the following (any missing component is assumed to be zero):

\e[attribute code;text color code;background color codem
The values for these are:
Attribute codes:
----------------
0=none 1=bold 4=underscore 5=blink 7=reverse 8=concealed
Text color codes:
-----------------
30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
Background color codes:
----------------------
40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
The effect is ended by specifying:
\e[0m
For example, to print out the string Hello in red:
printf("\e[0;31mHello\e[0m");
To print it out in bold blue:
printf("\e[1;34mHello\e[0m");