1 / 36

C Programming

C Programming. 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.

cody
Télécharger la présentation

C Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 eric raymond 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

  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

  10. The basic logic display 24 lines display “more” message display 1 line get input yes a space ? no no no Enter ? error ‘q’ ? yes yes Quit

  11. Code #include <stdio.h> #include <stdlib.h> the libraries we #include are not the same as you used in C++.

  12. <assert.h> assertions <ctype.h> character tests, e.g. isnum( ) <errno.h> error codes reported by system calls <limits.h> implementation defined limits <math.h> math functions <stdio.h> standard input and output <stdlib.h> standard utility functions and definitions EXIT_FAILURE EXIT_SUCCESS NULL <unistd.h> unix specific declarations and constants on OS/X the standard header files are in /usr/include

  13. Code #include <stdio.h> #include <stdlib.h> #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.

  14. Code #include <stdio.h> #include <stdlib.h> #define PAGELEN 24 #define LINELEN 512 void do_more(FILE*); int see_more( ); this is file “handle” It is a pointer to a file control block created when a file is opened. More on this later. function prototypes

  15. 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.

  16. mine -c 10 2.0 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

  17. mine -c 10 2.0 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.

  18. argv[ ] ‘m’ ‘i’ ‘n’ ‘e’ ‘\0’ [0] [1] [2] [3] [4] ‘-’ ‘c’ ‘\0’ ‘1’ ‘0’ ‘\0’ ‘2’ ‘.’ ‘0’ ‘\0’ NULL the argv array

  19. int main (int argc, char *argv[ ]) { FILE* fp; if (argc == 1) do_more(stdin); Declare a File Handle 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.

  20. int main (int argc, char *argv[ ]) { FILE* fp; if (argc == 1) do_more(stdin); else { while( --argc ) { . . . } In the C language, TRUE is represented as a non-zero value. FALSE is represented as zero. This loop repeats for each argument on the command line When you run out of arguments (argc = 0) drop out of the loop.

  21. 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.

  22. 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!

  23. int main (int argc, char *argv[ ]) { FILE* fp; if (argc == 1) do_more(stdin); else { while( --argc ) { fp = fopen( *++argv, “r”); if (fp != NULL) { . . . } 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). 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. fopen is a C language call. It tries to open the file. If the file opens, a pointer to the FILE is returned.

  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) { 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)

  25. 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.

  26. 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.

  27. 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) { 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. fgets( ) reads a string1 - similar to getline in C++ It reads from the stream2pointed 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. 1In 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.

  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) { reply = see_more( ); if (reply == 0) break; num_of_lines -= reply; } Test to see if the screen is full. 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

  29. 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.

  30. 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.

  31. 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; }

  32. Program Termination Normal program termination occurs under the following conditions: * a return from main( ) * an implicit return from main( ) * call to exit( )

  33. 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.

  34. 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).

  35. The end

More Related