Should we delete all the files? (Example) From last lecture: Why use a file at all? Asst 1a. Assignment 1. Sample code.

Similar documents
Introduction to C. CS2023 Winter 2004

Fundamental of Programming (C)

Chapter 7. Basic Types

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Work relative to other classes

Fundamentals of Programming

Computers Programming Course 5. Iulian Năstac

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

A Fast Review of C Essentials Part I

Fundamentals of Programming

Fundamental of Programming (C)

THE FUNDAMENTAL DATA TYPES

File Handling in C. EECS 2031 Fall October 27, 2014

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Topic 6: A Quick Intro To C

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Basic Types and Formatted I/O

Lecture 03 Bits, Bytes and Data Types

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

Types, Operators and Expressions

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

UNIT- 3 Introduction to C++

Programming Language Basics

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

These are reserved words of the C language. For example int, float, if, else, for, while etc.

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Types, Operators and Expressions

C Programming Language (Chapter 2 of K&R) Variables and Constants

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

C Language, Token, Keywords, Constant, variable

Arrays, Strings, & Pointers

CSC 1107: Structured Programming

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

C-programming. Goal To give basic knowledge of the C language. Some previous experiences in programming are assumed. Litterature

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Standard I/O in C and C++

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

CSC 1107: Structured Programming

Full file at

Chapter 11 Introduction to Programming in C

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Chapter 11 Introduction to Programming in C

The C language. Introductory course #1

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Programming in C. Week Tiina Niklander. Faculty of Science

Data Type Fall 2014 Jinkyu Jeong

Chapter 11 Introduction to Programming in C

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

BLM2031 Structured Programming. Zeyneb KURT

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Stream Model of I/O. Basic I/O in C

CSCI 171 Chapter Outlines

Programming. Elementary Concepts

Chapter 11 Introduction to Programming in C

Chapter 2. Procedural Programming

CS3157: Advanced Programming. Outline

LESSON 4. The DATA TYPE char

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Continued from previous lecture

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

Princeton University COS 333: Advanced Programming Techniques A Subset of C90

SU 2017 May 11/16 LAB 2: Character and integer literals, number systems, character arrays manipulation, relational operator

Structure of this course. C and C++ Past Exam Questions. Text books

C Overview Fall 2014 Jinkyu Jeong

Computer System and programming in C

An overview of Java, Data types and variables

Program Fundamentals

Visual C# Instructor s Manual Table of Contents

Fundamental of Programming (C)

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Programming in C and C++

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Chapter 11 Introduction to Programming in C

CSE 303 Lecture 8. Intro to C programming

Should you know scanf and printf?

3. Java - Language Constructs I

Lecture 02 C FUNDAMENTALS

Chapter 11 Introduction to Programming in C

EL2310 Scientific Programming

Arithmetic Operators. Portability: Printing Numbers

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Variables and literals

COP 3275: Chapter 07. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Presented By : Gaurav Juneja

Lecture 3. More About C

Transcription:

From last lecture: Why use a file at all? Put the temporary result in a variable? x=`date` But, grep only works with files! if date grep Mon > /dev/null then echo Another week starts. fi Should we delete all the files? (Example) for fn in * do echo Should I delete file $fn read ok if test $ok = yes then echo deleting $fn sleep 2 rm $fn fi done Assignment 1 Write a program exclusively in java to accomplish one of the following. Explain why you chose the task you solved, and why to did not implement each of the others. Word Counting: for each of the files in a given directory count the number of words in the file. Words are any sequence of non-blank non-tab characters separated by one or more blanks. Print a summary showing how many words of each length you found, as follows: 1 letter: 54 words 2 letters: 87 words etc. Asst 1a For word counting, you must do the word count for all the files in the directory, but you must not be required to type the file names by hand! Any string of non-blanks should count as a word. Sample code The following code can be found via the class web page. It reads a file and writes it out again. import java.io.*; public class Copy { public static void main(string[] args) throws IOException { File inputfile = new File("farrago.txt"); File outputfile = new File("outagain.txt"); UNIX introduction FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read())!= -1) out.write(c); in.close(); out.close(); 1

Revised outline External file... Chapter 1: Introduction Introduction: Preview Introduction: About C History of C. 1972: The C programming language developed by Dennis Ritchie Two programming paradigms; objected oriented and procedural. 1973: C used to write the Unix operating system. Comparison of Java and C. Software development process. Programming idiom. 1978: Kernighan and Ritchie set the first standard of C K&R standard 1989: the American National Standards Institute adopted the ANSI C standard Introduction: Programming paradigms object-oriented programming paradigm, based on the following design rule: decide which classes you need, provide a full set of operations for each class, and make commonality explicit by using inheritance. Introduction: Comparison of C and Java primitive data types: character, integer, and real In C, they are of different sizes, there is no Unicode 16-bit character set procedural programming paradigm, based on the following design rule: decide which procedures and data structures you want and use the best algorithms. structured data types: arrays, structures and unions. In C, arrays are static there are no classes Control structures are similar Functions are similar 2

Comparison of C and Java Java references are called pointers in C. Java constructs missing in C: packages threads exception handling garbage collection standard Graphical User Interface (GUI) built-in definition of a string standard support for networking support for program safety. C provides: efficiency flexibility and power Why is C (still) useful? many high-level and low-level operations stability C is used: data compression, graphics and computational geometry databases, operating systems there are zillions of lines of C legacy code Development Process Programming Style and Idioms Four stages (you know this already) preprocessing editing compiling: translates source code -> object code linking: produces executable code Portable programs will run on any machine. Program correctness and robustness are most important than program efficiency C is OK with respect to portability, yet In C, it s MUCH easier (than in java) to create NON-PORTABLE code! Why? Programming style includes recommendations for: lexical conventions a convention for writing comments In a natural language, an idiom is a phrase that has a specific meaning such as don t pull my leg while(*p++ = *q++) ; You'll learn how to identify, create and use idioms. 2: General Documentation Chapter 2: Example of a C Program Comments in C are similar to those in Java. There is no standard tool such as javadoc to produce documentation in HTML form. An in-line comment, starting with //, is not supported. The heading comment that starts the sample program follows a particular style convention used throughout this book. It always describes the intended meaning of the program, any known bugs, etc. 3

documentation /* Author: Tomasz Muldner * Date: August, 1999 * Version: 2.0 * File: Sample.c * Program that expects one or two filenames on the * command line and produces a hexadecimal dump of the * file whose name is passed as the first argument. If * the second argument is present, the dump is stored in * the file whose name is passed as this argument. * Otherwise, the dump is displayed on the screen. * The format of the dump is as follows: * Each line contains 16 hexadecimal ASCII codes of the * corresponding 16 bytes read from the file; separated * by a blank. This line is followed by a line containing * the 16 corresponding characters, again separated by a * blank, with each non-printable character displayed * as a dot and other characters unchanged. */ 2: Run-time Libraries and Function: Declarations Include directives, starting with #include, are needed in C programs to include files, called header files, which typically have the.h extension. In my example, three files are included, respectively called stdio.h, ctype.h and stdlib.h. These header files contain declarations of various standard functions that are defined in the run-time libraries. 2: Global Definitions Global definitions define entities (such as variables), which are available to all the code that follows this definition. In my example there is a single global definition: FILE *outfile; that defines a file handle, available to all the code that follows it, both the hex() and main() functions. /* include files */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> header /* global definitions */ FILE *outfile; /* output file */ 2: Function Declaration and Definition definition A declaration merely provides a function prototype: void hex(unsigned char *, int ); The declaration does not say anything about the implementation The definition of a function includes both the function prototype and the function body, where the body is the implementation of the function /* Function declaration */ /* * Function: hex(p, max) * Purpose: writes to the global output file * outfile the hexadecimal codes of max number of * characters originating at the address given by the * pointer p. This line is followed by the * corresponding chars. * Assumes that the file outfile has been * opened for output. * Inputs: p, max (parameters) * outfile (global variable) * Returns: nothing * Modifies: outfile * Error checking: none */ void hex(unsigned char *p, int max); 4

2: The main Function main Every C program must include a function called main: int main(int argc, char *argv[]) main() is an integer function, and returns one of two standard return codes: EXIT_FAILURE EXIT_SUCCESS. int main(int argc, char *argv[]) { FILE *infile; /* input file handle */ int i, tofile; const int SIZE = 16; unsigned char line[size]; /* local buffer */ if(argc > 3 argc < 2) { fprintf(stderr, "usage: %s filename [filename2]\n", argv[0]); return EXIT_FAILURE; outfile = stdout; /* set default output stream */ tofile = (argc == 3); /* is there an output file */ /* open I/O files */ if((infile = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "Cannot open file %s\n", argv[1]); return EXIT_FAILURE; main main if(tofile && (outfile = fopen(argv[2], "w")) == NULL) { fprintf(stderr, "Cannot open file %s\n", argv[2]); fclose(infile); return EXIT_FAILURE; /* main loop; reads SIZE bytes at a time; * stores them in line, and calls hex() */ while((i = fread(line, 1, SIZE, infile)) > 0) hex(line, i); /* close I/O */ if(fclose(infile) == EOF) { fprintf(stderr, "Cannot close file %s\n", argv[1]); if(tofile) fclose(outfile); return EXIT_FAILURE; if(tofile && fclose(outfile) == EOF) { fprintf(stderr, "Cannot close file %s\n", argv[2]); return EXIT_FAILURE; return EXIT_SUCCESS; main /* Definition of hex() */ void hex(unsigned char *p, int max) { int i; unsigned char *paux; for(i = 0, paux = p; i < max; i++, paux++) fprintf(outfile, "%02x ", *paux); fputc('\n', outfile); for(i = 0, paux = p; i < max; i++, paux++) fprintf(outfile, "%c ", isprint(*paux)? *paux : '.'); fputc('\n', outfile); Chapter 3: Lexical Structure, Primitive Data Types and Terminal I/0 5

3: Preview 3: Lexical Structure C is a free format language: primitive data types: int, char, float, double, and their variants, such as long double. expressions, including the assignment expressions EVERYTHING IS AN EXPRESSION! if ( (i = bar(3)) == j ) OR i=bar(3)) ; if (i) { basic terminal I/O i= bar ( 3); i /*hello*/ = b/* me too */ar(3); any sequence of whitespace characters can be used in the place of a single whitespace character type conversions and ways of defining synonyms for existing data types. Aside: A program is lexically correct if it follows the lexical structure of the language: it contains only characters from the language s alphabet all its tokens are built according to the language s rules. 3: Comments /* Hello */ Wrong: /* outer /* inner */ */ The book says these are wrong, but // foo /* my great code *. i = bar (3) /* the end */ J=k; /*/* bar */ Comments if(isdigit) /* error */ Comments and Identifiers /* * Program to sort integer values */ k++; /* k is incremented by 1*/ Make every comment count. Don't over-comment. This is not usually as much of a problem as under-commenting (which is frequent), but it s worth noting. Make sure comments and code agree. How can this fail to be the case, you ask? 6

3: Line Structure, Identifiers Two lines my\ id are joined during compiler translation into myid Identifiers The documentation of programs should make it clear whether you are using identifiers whose length exceeds 6 characters. Never use identifiers that have more than 31 characters. An identifier is a sequence of letters, digits, and underscores that does not start with a digit (case-sensitive, but only the first 31 characters are significant) 3: Primitive Data Types Identifiers Use a consistent style throughout your code. Variables should have meaningful names when appropriate. There are some cultural factors here. E.g. The names i, j. k are stereotypically known to refer to loop index variables and are suitable for short loops. You are encouraged to mix case to make your identifiers more readable: longidentifier C provides several primitive data types: char, int, float and double. No built-in Boolean type; instead use int: the value 0 stands for false, any non-zero value stands for true No guarantee that a specific amount of memory will be allocated to a particular data type. All implementations of C must follow certain rules. 3: Memory and Range of Values Computer memory consists of words; each word consists of a number of bytes, a byte consists of a number of bits (usually 8 bits). Signed integers use the leftmost bit (sign bit), to represent the sign. The largest unsigned 16-bit integer: 2 16-1 The largest signed 16-bit integer: 2 15-1 C provides a header file limits.h, it defines e.g. CHAR_BIT - the width of char type in bits (>= 8) INT_MAX is the maximum value of int (>= 32,767). plain, signed and unigned 3: Integer Types short unsigned int signed long int size(short) <= size(int) <= size(long) Arithmetic operations on unsigned integers follow the rules of arithmetic modulo 2 n. Therefore, they can not produce an overflow 7

Ranges To support portability, use only integers in the ranges specified in limits.h For example, you can always use plain integers in the range from - 32,767 to 32,767 Any other assumptions, such as that the size of an int is 4 bytes, must not be made. In order to check whether the sum of two integers i and overflows, do not use i + j > INT_MAX Instead, use Overflow i > INT_MAX - j 3: Character Types Characters There are three character data types in C: (plain) char unsigned char signed char Character types are actually represented internally as integers (unsigned or signed). In order to write portable code, you should explicitly specify signed char or unsigned char. You should never make any assumptions about the code values of characters, such as that the value of 'A' is 65. Two popular character sets: ASCII (American Standard Code for Information Interchange) EBCDIC (used by IBM computers) float double long double 3: Floating-point Types Use float.h for sizes and ranges. Only guarantee: 3: Declarations of Variables and Constants int i; /* initial value undefined */ double d = 1.23; const double PI = 3.1415926; size(float) <= size(double) <= size(long double) 8

Declarations A declaration of a different data type starts on a new line. The lists of identifiers are aligned to start in the same column. Each variable identifier is followed by one space. Each declaration that contains an initialization appear on a separate line: int i = 1; int j = 2; Declarations If comments are required, each declaration should be placed on a separate line: int lower; /* lower bound of the array */ int upper; /* upper bound of the array */ Names of constants will appear in upper case and const always appears in front of the declaration. 3: Assignments 3: The Main Program An l-value: an expression that can be interpreted as an address. Examples: a variable is an l-value, a constant is not. x = y = z; /* exactly one space before and after = */ A program consists of one or more functions. There must be exactly one occurrence of main(): int main(int argc, char *argv[]) int main() main() is an integer function, which returns one of two standard codes: EXIT_FAILURE and EXIT_SUCCESS (defined in the standard library stdlib.h) Other values will not be portable. Main The main function looks as follows: int main() { the left brace on the same line as the header body body indented to the right the matching right brace aligned with int Main Function main() is an integer function, which returns one of two standard return codes: EXIT_FAILURE EXIT_SUCCESS 9

3: Literal Constants integer: 123 47857587L String and Character Constants floating point: 12.66 23478.78899E-20 character: '\n' 'd' string: "abc" String constants and character constants are very different: "a" 'a' 3: Expressions logical AND, as in e1 && e2 The expression a < b < c Associativity logical OR, as in e1 e2 a conditional expression, as in e1? e2 : e3 a comma expression, as in e1, e2 is interpreted as a < b < c and has a different meaning than a < b && b < c Spacing Don't use spaces around the following operators: ->. []! ~ ++ -- - (unary) * (unary) & In general, use one space around the following operators: = +=?: + < && + (binary) etc. Examples a->b a[i] *c a = a + 2; a= b+ 1; a = a+b * 2; #include <stdio.h> 3: Terminal I/O Standard input is usually a keyboard, unless it has been redirected Standard output is usually the screen, unless it has been redirected EOF is a constant defined in stdio.h; it stands for End-Of-File. I/O redirection: F < test.in > test.out 10

3: Single Character I/O Our first program int getchar() to input a single character int putchar(int) to output a single character These read and write to standard input and output: stdin & stdout. start with main main() { read a character with getchar() char c; --------- int c; c = getchar(); print it with putchar() putchar( c ); /* File: ex1.c * Program that reads a single character and * outputs it, followed by end-of-line */ #include <stdio.h> #include <stdlib.h> int main() { int c; /* chars must be read as ints */ c = getchar(); putchar(c); putchar('\n'); Include statements will not be shown in other examples Example Read Single Character if((c = getchar()) == EOF) /* error, else OK */ } return EXIT_SUCCESS; Placement of brackets: Errors Another Example if(c = getchar() == EOF) The compiler interprets it as follows: if(c = (getchar() == EOF)) is it and EOF ( 0 or (-1)) assign that to c (c gets 0 or -1) /* * Program that reads two characters and * prints them in reverse order, separated * by * a tab and ending with end of line. * Error checking: Program terminates if * either of the input operations fails. * No error checking for the output */ 11

Example Example if((d = getchar()) == EOF) return EXIT_FAILURE; int main() { int c, d; Idiom? putchar(d); putchar('\t'); putchar(c); putchar('\n'); if((c = getchar()) == EOF) return EXIT_FAILURE; /* no output! */ } return EXIT_SUCCESS; /* Read a single character, if it is lower case * 'a' then output 'A'; otherwise output the input * character. Finally, output the end-of-line */ int main() { int c; if((c = getchar()) == EOF) return EXIT_FAILURE; "Read Single Character"Idiom 3: Formatted I/O printf printf() is the function that prints stuff on the standard output stream. int printf("format", exp) printf("%d", 123); print formatted printf("the value of i = %d.\n", i); if(c == 'a') putchar('a'); else putchar(c); putchar('\n'); Example printf("hello world\n"); (void)printf("hello world\n"); /* document.*/ } return EXIT_SUCCESS; if(printf("hello world\n") == EOF)... printf() expects a string (and maybe some other arguments) so printf("\n"); is correct, but printf('\n'); is wrong. Getting input: scanf: takes a format string: what to expect Codes for different types of data are one character each(!) takes additional arguments that are addresses: location in memory in which to deposit the results. Boils down to saying, for example: read an integer in decimal and a single charcter and put them at memory address 512 and 890 12

3: Formatted I/O scanf Assignment change C int scanf("format", &var) read formatted where format is actually a special set of symbols. int i; double d; scanf("%d", &i); scanf("%lf", &d); scanf("%d%lf", &i, &d); int main() { int i; Example printf("enter an integer:"); scanf("%d", &i); printf("%d\n", i); Idiom? 3: Formatted I/O. Integer Conversions To print integers, the following conversions are used: d signed decimal ld long decimal u unsigned decimal (uncommon) o unsigned octal (uncommon) x, X unsigned hexadecimal (uncommon) return EXIT_SUCCESS; printf("%d%o%x", 17, 18, 19); 3: Formatted I/O Float Conversions To print floating point values, the following conversions are used (the default precision is 6): f [-] ddd.ddd e [-] d.ddddde{sign}dd E [-] d.ddddde{sign}dd g shorter of f and e G shorter of f and E printf("%5.3f\n", 123.3456789); printf("%5.3e\n", 123.3456789); 123.346 1.233e+02 double fv; long lv; printf("%lf", fv); scanf("%f", &fv); printf("%ld", lv); scanf("%d", &lv); printf("%d", 3.5); printf("%g", 4); 13

3: Formatted I/O String Conversions To print characters and strings, the following conversions are used: c character s character string char *s1 = "outputs"; char *s2 = "strings"; printf("%c", 'a'); printf("%d", 'a'); printf("this %s a test", "is"); printf("this line %s %s\n", s1, s2); > This line outputs strings 3: Formatted I/O More on scanf() scanf() returns the number of items that have been successfully read, and EOF if no items have been read and end-file has been encountered. For example scanf("%d%d", &i, &j) returns the following value: 2 if both input operations were successful 1 if only the first input operations was successful 0 if the input operation failed EOF if an end-of-file has been encountered. Example int main() { double i, j; printf("enter two double values:"); if(scanf("%lf%lf", &i, &j)!= 2) return EXIT_FAILURE; Idiom? Read Single Integer with prompt printf("enter integer: "); if(scanf("%d", &i)!= 1 ) /* error, else OK */ } printf("sum = %f\ndifference = %f\n", i + j, i - j); return EXIT_SUCCESS; Read Two Integers if(scanf("%d%d", &i, &j)!= 2 ) /* error, else OK */ sizeof(type name) or sizeof expression 3:sizeof 3:Type Conversions Type T is wider than type S (and S is narrower than T), if returns the size of the data type or object represented by the expression. sizeof(int) sizeof i sizeof(t) >= sizeof(s) The narrower type is promoted to the wider type, the wider type is demoted to the narrower type an int value can be safely promoted to double a double value can not be safely demoted to int 14

3: Arithmetic Conversions If operands of an expression are of different types, then these operands will have their types changed, using arithmetic conversions. A lower precision type is promoted to a higher precision type according to the following hierarchy: int unsigned long unsigned long float double long double 3: Assignment and Type Cast Conversions Assignment conversions occur when the expression on the right hand side of the assignment has to be converted to the type of the left-hand side. The type cast expression (typ) exp converts the expression exp to the type typ. double f, c; f = 10; /* assignment conversion */ f = 100.2; c = (5/9)*(f - 32); c = ( (double)5/9 ) * (f - 32); /* cast */ 3: Type Synonyms: typedef typedef existingtype NewType; For example, if you want to use a Boolean type, define typedef int Boolean; Lexical recommendations Blank lines are used to separate logically related sections of code When specifying a new type using typedef, identifier names start with an upper case letter. Boolean b = 1; 15