C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There...

36
C Programming C Programming
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    226
  • download

    3

Transcript of C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There...

Page 1: 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.

C ProgrammingC ProgrammingC ProgrammingC Programming

Page 2: 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.

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

Page 3: 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.

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

Page 4: 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.

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.

Page 5: 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.

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.

Page 6: 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.

An Illustration of a C Program and the logic behind it’s development

Page 7: 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.

Programming the more commandThis example comes largely from chapter 1 of the Molay book.

Page 8: 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.

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 yourUnix system by writing additional programsand storing the executable in one of thesystem directories, e.g. /bin or /usr/bin.

Page 9: 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.

Requirements: What does more do?

We can learn almost everything we need to knowin Unix from the operating system itself!

* read the man pages - follow “see also” links* read header files* try the command

Page 10: 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.
Page 11: 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.

The basic logicdisplay 24 lines

display “more”message

get input

aspace

?

yes

‘q’?

Quit

yes

noEnter

?

yes

no

display 1 line

noerror

Page 12: 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.

Code

#include <stdio.h>#include <stdlib.h>

the libraries we #include are notthe same as you used in C++.

Page 13: 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.

<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_FAILUREEXIT_SUCCESSNULL

<unistd.h> unix specific declarations and constants

on OS/X the standard header files are in /usr/include

Page 14: 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.

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 valueis substituted in its place by the pre-processor.

This is the way that C handles the definition of constants.

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

Code

#include <stdio.h>#include <stdlib.h>

#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 filecontrol block created when a file is opened.More on this later.

Page 16: 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.

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

these parameters allow you to pass commandline arguments to your program. argc is the number of command line arguments, it includes the command itself. argv is an array of char pointers.

Page 17: 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.

A command line consists of a number of tokens that areseparated by white space. Each token is a string of characterscontaining 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

Page 18: 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.

The shell parses the command line into tokens and passesthe result to the program being called in the form of an array of char pointers.

mine -c 10 2.0

Page 19: 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.

argv[ ]

[0]

[1]

[2]

[3]

[4]

‘m’ ‘i’ ‘n’ ‘e’ ‘\0’

‘-’ ‘c’ ‘\0’

‘1’ ‘0’ ‘\0’

‘2’ ‘.’ ‘0’ ‘\0’

NULL

the argv array

Page 20: 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.

int main (int argc, char *argv[ ]){ FILE* fp;

if (argc == 1) do_more(stdin);

The first step in any command line programis to process the argument array.

if argc is equal to 1, there was only 1argument on the command line, and it is thecommand itself. In this case, our more programwill take its input from stdin.

Declare a File Handle

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

int main (int argc, char *argv[ ]){ FILE* fp;

if (argc == 1) do_more(stdin); else { while( --argc ) { . . . }

This loop repeats for eachargument on the command line

In the C language, TRUE isrepresented as a non-zerovalue. FALSE is represented aszero.

When you run out of arguments (argc = 0)drop out of the loop.

Page 22: 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.

Making Library Function Calls

fp = fopen( *++argv, “r”);

almost every function call returns some specificvalue 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 alsosets a global variable, errno.

Page 23: 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.

Making Library Function Calls

Good programming practice in Unix programmingrequires that return values always be tested to seeif the function call was successful. If it was not, thenappropriate error handling must take place.

You will be expected to follow this practice!

Page 24: 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.

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. Ifthe file opens, a pointer tothe FILE is returned.

The “r” says open thefile for reading only.

If the open fails, a NULLpointer is returned. We willhandle the error on the next slide.

pre-increment to get the nextargument in the argument array.(The first argument is the command itself)

De-refrence the pointer to getthe text string (in this case a file name).

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

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 messageto stderr. It prints the string passedas a parameter, followed by a colon, and then a system error messagefor the last library call to produce an error (error number stored in errno)

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

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.

Page 27: 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.

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.

Page 28: 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.

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 string1 - similar to getline in C++ It reads from the stream2 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 isreturned. A NULL (or zero) is interpreted as FALSE in C.So, this while loop reads linesfrom the file until there is no moredata to read.

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 tothe stream of data in a file.

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

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 andreturns 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 screenis full.

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

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 thedesignated stream. If anerror occurs, the callreturns EOF.

Page 31: 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.

The see_more( ) functionint 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 theoperation fails, it returns EOF.

Page 32: 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.

The see_more( ) functionint 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;}

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

Program Termination

Normal program termination occurs under the following conditions:

* a return from main( ) * an implicit return from main( ) * call to exit( )

Page 34: 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.

Homework Assignment:

1) Read chapters 1 and 2 in the Molay Book2) Study the code examples carefully3) Do programming project #2 - due by 1:00am Monday morning.

All of the C language constructs that you need to know for thisassignment have been discussed in this set of slides and thecompanion discussion in the Molay book.

Page 35: 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.

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

Page 36: 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.

The end