Download presentation
Presentation is loading. Please wait.
1
C Programming
2
C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects to do I/O C has no try...catch blocks C has no new operator C programmers love pointers No TRUE and FALSE
3
The “Unix” Philosophy 1. The Rule of Modularity: Write simple parts connected by clean interfaces 2. The Rule of Clarity: Clarity is better than cleverness. 3. The Rule of Composition: Design programs to be connected to other programs. 4. The Rule of Simplicity: Design for simplicity. Add complexity only where you must eric raymond
4
The “Unix” Philosophy 5. The Rule of Parsimony: Write big programs only when it is clear by demonstration that nothing else will do. 6. The Rule of Transparency: Design for visibility to make inspection and debugging easier. 7. The Rule of Least Surprise: In interface design, always do the least surprising thing. 8. The Rule of Silence: When a program has nothing to say, it should say nothing.
5
The “Unix” Philosophy 9. The Rule of Repair: When you must fail, fail noisily and as soon as possible. 10. The Rule of Optimization: Get it working before you optimize it. 11. The Rule of Diversity: Distrust all claims of “the only true way”. 8. The Rule of Extensibility: Design for the future, it will be here sooner than you think.
6
An Illustration of a C Program and the logic behind it’s development
7
Programming the more command This example comes largely from chapter 1 of the Molay book.
8
In Unix, commands that you enter on the command line are really all just programs. When you type the command, the shell executes that program. So... you can add new commands to your Unix system by writing additional programs and storing the executable in one of the system directories, e.g. /bin or /usr/bin.
9
Requirements: What does more do? We can learn almost everything we need to know in Unix from the operating system itself! * read the man pages - follow “see also” links * read header files * try the command
11
The basic logic display 24 lines display “more” message get input a space ? yes ‘q’ ? Quit yes no Enter ? yes no display 1 line no error
12
Code #include the libraries we #include are not the same as you used in C++.
13
assertions character tests, e.g. isnum( ) error codes reported by system calls implementation defined limits math functions standard input and output standard utility functions and definitions EXIT_FAILURE EXIT_SUCCESS NULL unix specific declarations and constants on OS/X the standard header files are in /usr/include
14
Code #include #define PAGELEN 24 #define LINELEN 512 #define - defines a value to associate with a name. Wherever the name is used in a program, the value is substituted in its place by the pre-processor. This is the way that C handles the definition of constants.
15
Code #include #define PAGELEN 24 #define LINELEN 512 void do_more(FILE*); int see_more( ); function prototypes this is file “handle” It is a pointer to a file control block created when a file is opened. More on this later.
16
int main (int argc, char *argv[ ]) { these parameters allow you to pass command line arguments to your program. argc is the number of command line arguments, it includes the command itself. argv is an array of char pointers.
17
A command line consists of a number of tokens that are separated by white space. Each token is a string of characters containing no spaces, unless the string is enclosed in quotes. The first token is the command itself, followed by its arguments mine -c 10 2.0
18
The shell parses the command line into tokens and passes the result to the program being called in the form of an array of char pointers. mine -c 10 2.0
19
argv[ ] [0] [1] [2] [3] [4] ‘m’ ‘i’ ‘n’ ‘e’ ‘\0’ ‘-’ ‘c’ ‘\0’ ‘1’ ‘0’ ‘\0’ ‘2’ ‘.’ ‘0’ ‘\0’ NULL the argv array
20
int main (int argc, char *argv[ ]) { FILE* fp; if (argc == 1) do_more(stdin); The first step in any command line program is to process the argument array. if argc is equal to 1, there was only 1 argument on the command line, and it is the command itself. In this case, our more program will take its input from stdin. Declare a File Handle
21
int main (int argc, char *argv[ ]) { FILE* fp; if (argc == 1) do_more(stdin); else { while( --argc ) {... } This loop repeats for each argument on the command line In the C language, TRUE is represented as a non-zero value. FALSE is represented as zero. When you run out of arguments (argc = 0) drop out of the loop.
22
Making Library Function Calls fp = fopen( *++argv, “r”); almost every function call returns some specific value to indicate that an error occurred in the function. fopen( ) returns a FILE* if the open is successful, otherwise it returns a NULL. When an error value is returned, the function also sets a global variable, errno.
23
Making Library Function Calls Good programming practice in Unix programming requires that return values always be tested to see if the function call was successful. If it was not, then appropriate error handling must take place. You will be expected to follow this practice!
24
int main (int argc, char *argv[ ]) { FILE* fp; if (argc == 1) do_more(stdin); else { while( --argc ) { fp = fopen( *++argv, “r”); if (fp != NULL) {... } fopen is a C language call. It tries to open the file. If the file opens, a pointer to the FILE is returned. The “r” says open the file for reading only. If the open fails, a NULL pointer is returned. We will handle the error on the next slide. pre-increment to get the next argument in the argument array. (The first argument is the command itself) De-refrence the pointer to get the text string (in this case a file name).
25
int main (int argc, char *argv[ ]) { FILE* fp; if (argc == 1) do_more(stdin); else { while( --argc ) { fp = fopen( *++argv, “r”); if (fp != NULL) { do_more(fp); close(fp); } else { perror(“file error”); exit(1); } return 0; } perror prints an error message to stderr. It prints the string passed as a parameter, followed by a colon, and then a system error message for the last library call to produce an error (error number stored in errno )
26
Guidelines for writing your own functions Make use of return values to make error processing easy for the calling program. Do not exit from inside of a function. Make functions as general as possible. Use system defined limits - not arbitrary ones Don’t re-invent the wheel - use standard library functions when possible. Don’t use static variables or dynamic allocation when automatic allocation will do.
27
Guidelines for writing your own functions Make sure that your program frees all dynamically allocated memory. Carefully consider functions that may be called recursively, in a signal handler, or in a thread. Functions with static variables may not work as you expect. Analyze the consequences of being interrupted by a signal.
28
The do_more( ) function void do_more(File* fp) { char line[LINELEN]; int num_of_lines = 0; int reply; while (fgets(line, LINELEN, fp) ) { if (num_of_lines == PAGELEN) { fgets( ) reads a string 1 - similar to getline in C++ It reads from the stream 2 pointed to by fp It reads until it encounters a new line character, until it encounters the end of the stream, or until it reads LINELEN-1 characters. The stored string is null terminated. The newline character, if read, is stored in the string. if fgets fails, a NULL is returned. A NULL (or zero) is interpreted as FALSE in C. So, this while loop reads lines from the file until there is no more data to read. 1 In C, there is no string class. The term string here refers to a null terminated char array. 2 In C, there are no stream classes. The term stream refers to the stream of data in a file.
29
The do_more( ) function void do_more(File* fp) { char line[LINELEN]; int num_of_lines = 0; int reply; while (fgets(line, LINELEN, fp) ) { if (num_of_lines == PAGELEN) { reply = see_more( ); if (reply == 0) break; num_of_lines -= reply; } see_more( ) prompts the user and returns the number of lines to read next (1 or 24), or a zero to quit. break out of the while loop Test to see if the screen is full.
30
void do_more(File* fp) { char line[LINELEN]; int num_of_lines; int reply; while (fgets(line, LINELEN, fp) ) { if (num_of_lines == PAGELEN) { reply = see_more( ); if (reply == 0) break; num_of_lines -= reply; } if ( fputs ( line, stdout) == EOF) exit(1); num_of_lines++; } fputs send a string to the designated stream. If an error occurs, the call returns EOF.
31
The see_more( ) function int see_more( ) { int c; printf(“more?”); while (c = getchar( ) ) != EOF) { printf outputs data to stdout... sort of like using stream insertion. getchar gets 1 character from stdin. If the operation fails, it returns EOF.
32
The see_more( ) function int see_more( ) { int c; printf(“more?”); while (c = getchar( ) ) != EOF) { if (c == ‘q’) return 0; if (c == ‘ ‘) return PAGELEN; if (c == ‘\n’) return 1; } return 0; }
33
Program Termination Normal program termination occurs under the following conditions: * a return from main( ) * an implicit return from main( ) * call to exit( )
34
Homework Assignment: 1) Read chapters 1 and 2 in the Molay Book 2) Study the code examples carefully 3) Do programming project #2 - due by 1:00am Monday morning. All of the C language constructs that you need to know for this assignment have been discussed in this set of slides and the companion discussion in the Molay book.
35
Copy stdin to stdout when no file name is given as a parameter to the command. Copy the contents of a file to stdout when the filename is given as a parameter to the command. Print an appropriate message when the named file cannot be opened. Print an appropriate message if a read operation fails while reading data from the file. Insert line numbers into the ouptut when the -n option is used in the command. Print an appropriate message for invalid options on the command line (anything other than -n).
36
The end
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.