C part 2 - California State University, Northridge



Spring 2002 COMP 122 Peter Smith

Handout #8

C – Part 2

In this handout we look at some features of C that you will probably not need this semester but will be handy in future classes.

Redirection of input and output

When running programs in a Unix environment, a simple way to read data from a file into a program and to save results and/or error messages to a file without making any changes to the program source code is to use the Unix shell redirection.

A C program has three built-in file streams: stdin, stderr and stdout. When you use scanf you are reading from stdin. When you use printf you are writing to stdout.

The following table shows how you can redirect the three streams when calling a.out.

|Command |Stdin |Stdout |Stderr |

|a.out |Keyboard |Screen |Screen |

|a.out < Datafile |Datafile |Screen |Screen |

|a.out > Results |Keyboard |Results |Screen |

|a.out < Datafile > Results |Datafile |Results |Screen |

|a.out >& Allout |Keyboard |Allout |Allout |

|a.out < Datafile >& Allout |Datafile |Allout |Allout |

|(a.out > Results) >& Errors |Keyboard |Results |Errors |

|(a.out < Datafile > Results) >& Errors |Datafile |Results |Errors |

Later we look at attaching files to programs in general.

Command line arguments

In general, the main program function can have the following heading

main(int argc, char *argv[])

When the program runs, the operating system puts into argc (argument count) the number of tokens on the command line. This count includes the program name itself. Pointers to the texts of the tokens is put into the elements of argv (argument vector). Here is a simple program; it just echoes the components of the command line back to the standard output.

Example 13

#include

int main (int argc, char* argv[])

{

int i;

printf("argc is: %d\n", argc);

for (i=0; ih.oidts< edulcni#

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download