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.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
CS 450 Module R1. R1 Introduction In Module R1, you will implement a user interface (command handler). There are a couple of options: ▫Command Line: interface.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 20 Arrays and Strings
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 14 - Advanced C Topics Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction.
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
Chapter 10.
CIS 101: Computer Programming and Problem Solving Lecture 8 Usman Roshan Department of Computer Science NJIT.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
Linux+ Guide to Linux Certification, Second Edition
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
Chapter 5: Loops and Files.
Concurrency Sharing of resources in the same time frame Apparent concurrency is sharing the same CPU, memory, or I/O device Real concurrency is sharing.
Guide To UNIX Using Linux Third Edition
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
chap13 Chapter 13 Programming in the Large.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
C for Java Programmers Tomasz Müldner Copyright:  Addison-Wesley Publishing Company, 2000 Introduction to C Muldner, Chapters 1, 2.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Linux+ Guide to Linux Certification, Third Edition
File IO and command line input CSE 2451 Rong Shi.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Minimal standard C program int main(void) { return 0 ; }
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
Files A collection of related data treated as a unit. Two types Text
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
1 Homework Continue with K&R Chapter 5 –Skipping sections for now –Not covering section 5.12 Continue on HW5.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
Linux Administration Working with the BASH Shell.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
User-Written Functions
Chapter 7: User-Defined Functions II
Sorting Tutorial Using C On Linux.
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
C Basics.
Programmazione I a.a. 2017/2018.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Chapter 14 - Advanced C Topics
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
File Input and Output.
Programming in C Miscellaneous Topics.
Programming in C Miscellaneous Topics.
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Presentation transcript:

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

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

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.

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.

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

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

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.

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

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

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

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

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.

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.

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.

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

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

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

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

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.

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.

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!

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

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 )

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.

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.

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.

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.

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.

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.

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

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

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.

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

The end