Tutorial #3
Zip tut3.zip
Command line arguments
You will often want to accept arguments from the command line. For example:
tut3> gcc ex1_hello.c -Wall -o ex1
tut3> ./ex1 Sonjia
Number of args: 2
Hello Sonjia!
tut3>
Source code for this program:
ex1_hello.c
Text
In this example:
- argc is the number of arguments to main
- argv is a array of pointers to strings, ie, an array of strings
Note that argv[0] is the name of the program, and the argv[1] is the first argument from the command line.
Files
C views a file as a continuous sequence of bytes, each of which can be read individually.
The operating uses a non-negative integer called a file descriptor
to manage files. 0, 1, and 2 are reserved for standard in, standard out, and
standard error, respectively.
Here we will use the system calls declared in fcntl.h,
open and creat
to open and create files. To open a file that already exists:
int open(char * name, int flags)
where flagsindicates if the file will be opened for reading, writing, or both:
- O_RDONLY - open for reading only
- O_WRONLY - open for writing only
- O_WRONLY | O_APPEND - open for writing only in append mode
- O_RDWR - open for both reading and writing
A file desciptor is returned if the call is sucessful. Example:
int f;
if ( ( f = open("/home/wax/myfile.txt",O_RDONLY,0)) == -1) {
printf("Error: can't open file");
...
}
To create a new file or to overwrite an existing file:
int creat(char * name, int perms);
Here, perms will be a 3-digit octel number (ie, prefixed with '0')
to indicate the read-write-execute permissions of the new file, similar to what you would use with the chmod shell command.
To read and write to a file, we use the system calls read and write
int write(int fd, const void *buf, size_t count);
int read(int fd, const void *buf, size_t count);
Example: ex2_filex.c
Text
Basic bit operations
C provids operators to examine an manipulate the invidual bits of a variable
- & - Bitwise AND
- | - Bitwise OR (inclusive OR)
- ~ - Bitwise XOR (exclusive OR)
- << - Left shift
- >> - Right shift
- ~ - One's complement, "inverts" bits
Example: ex3_bits.c
Text
Macros with arguments
We can use the #define preprocesssor with arguments, so that the replacement text varies by usage.
Example: ex4_macro.c
Text
We can use the gcc option -E to to review output from the preprocessor.