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

Similar documents
Types, Operators and Expressions

Types, Operators and Expressions

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CSC 1107: Structured Programming

File IO and command line input CSE 2451

Engineering Computing I

CS1100 Introduction to Programming

Lecture 02 C FUNDAMENTALS

Number Systems, Scalar Types, and Input and Output

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

The Design of C: A Rational Reconstruction (cont.)

Standard File Pointers

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

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

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -VARIABLE AND DATA TYPES- SPRING 2015, SEON-JU AHN, CNU EE

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

COMP327 Mobile Computing Session: Tutorial 2 - Operators and Control Flow

THE FUNDAMENTAL DATA TYPES

Input / Output Functions

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

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

Computer System and programming in C

Chapter 7. Basic Types

Arithmetic Operators. Portability: Printing Numbers

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

Programming. Elementary Concepts

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

Lecture 3. More About C

Reserved Words and Identifiers

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Internal representation. Bitwise operators

Work relative to other classes

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

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

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

High Performance Computing

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

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

A Fast Review of C Essentials Part I

Internal representation. Bitwise operators

Internal representation. Bitwise operators

Course organization. Course introduction ( Week 1)

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

JAVA Programming Fundamentals

System Software Experiment 1 Lecture 7

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

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

Continued from previous lecture

C programming basics T3-1 -

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

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

XC Specification. 1 Lexical Conventions. 1.1 Tokens. The specification given in this document describes version 1.0 of XC.

C-LANGUAGE CURRICULAM

Fundamentals of Programming. Lecture 11: C Characters and Strings

C: How to Program. Week /Mar/05

CSC 1107: Structured Programming

Computers Programming Course 5. Iulian Năstac

Fundamental of Programming (C)

CSC 1107: Structured Programming

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

UNIT- 3 Introduction to C++

Lecture 03 Bits, Bytes and Data Types

The Design of C: A Rational Reconstruction: Part 2

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Types, Variables, and Constants

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

EEE145 Computer Programming

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Advanced C Programming Topics

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

C - Basic Introduction

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Syntax and Variables

Chapter 2: Basic Elements of C++

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Fundamentals of Programming

Java Notes. 10th ICSE. Saravanan Ganesh

EL2310 Scientific Programming

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Chapter 2 - Introduction to C Programming

Should you know scanf and printf?

XSEDE Scholars Program Introduction to C Programming. John Lockman III June 7 th, 2012

CS Programming In C

OBJECT ORIENTED PROGRAMMING

Informatics Ingeniería en Electrónica y Automática Industrial

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

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

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

EL2310 Scientific Programming

Getting started with Java

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

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

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

Transcription:

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

Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically start with f: fopen() fgets() fprintf() etc. l stdio.h also defines the type FILE *f; l f is a pointer to a stream l A stream could be a file or stdin, stdout, stderr 2

Streams l printf() and scanf() have variants which operate on any stream: int fprintf(file *f,char *fmt, ); int fscanf(file *f, char *fmt, ); printf( hello ); is the same as fprintf(stdout, hello ); 3

Streams l To write something to stderr: fprintf(stderr, error!\n ); l Note that stdin is read-only and stdout and stderr are write-only, so fprintf(stdin, will not work ); will fail (but will not crash your program). 4

Streams l There are similar functions for getchar and putchar: int fgetc(file *stream); int fputc(int c, FILE *stream); 5

Line-based I/O l We ll mostly use: char *fgets(char *s,int n,file *f) l Reads at most one less than the number of characters specified by n from the given stream and stores them in the string s l If \n is read, it is also stored in the string l Note: we are not guaranteed a full line! 6

Opening and closing files FILE *fopen(char *f,char *mode); l Creates a new stream by opening a file whose name is in f l If it fails, returns NULL l To close the stream: int fclose(file *f); Note: When a program exits all open files are automatically closed 7

Stream Modes l The mode tells us whether we are reading or writing (it s a string) l r - read-only file must exist l w - write-only file is created if necessary, contents are destroyed on open l a - append (write-only) file is created if necessary, contents preserved (write at the end of the file) 8

An Example (filecopy.c) #include <stdio.h> int main() { } 9 FILE *f, *g; char str[100]; f = fopen("filecopy.c","r"); g = fopen("output.c","w"); while(fgets(str,100,f)) { } fprintf(g,"%s",str); fclose(f);

Status of Streams l int feof(file *f) - returns non-zero if EOF has been reached on f, 0 otherwise l int ferror(file *f) - returns nonzero if an error has occurred on f, 0 otherwise 10

Types, Operators, and Expressions EECS 2031 Fall 2014 October 27, 2014 11

Variable Names (2.1) l Combinations of letters, numbers, and underscore character ( _ ) that do not start with a number are not a keyword l Upper and lower case letters are distinct (x X) 12

Variable Names: Recommendations l Don t begin variable names with underscore _ l Limit the length of a variable name to 31 characters or less (extraneous characters may be ignored). l Function names, external variables: the limit may be as low as 6. l Lower case for variable names. l Upper case for symbolic constants #define MAX_SIZE 100 l Use short names for local variables and long names for external variables. 13

Data Types and Sizes (2.2) 4 basic types in C l char characters (8 bits) l int integers (either 16 or 32 bits) l float single precision floating point numbers (4 bytes) l double double precision floating point numbers (8 bytes) 14

Qualifiers l signed char sc; /* -127 +128 */ l unsigned char uc; /* 0 +255 */ l short s; /* 16 bits, -32,768 - +32,767 */ short int s; l long counter; /* 32 bits */ long int counter; int is either 16 or 32 bits, depending on systems. l signed int sint;/* same as int sint; */ l unsigned int uint; 0 +4,294,967,295, assuming 4-byte int l long double ld; /* 12 or 16 bytes */ 15

Qualifiers (numeric.c) l <limits.h> and <float.h> contain symbolic constants for all of the above sizes, other properties of the machine and compiler. l To get the size of a type, use sizeof( ) int_size = sizeof( int ); 16

Characters l 8 bits l Included between 2 single quotes char x ='A' l Character string: enclosed between 2 double quotes "This is a string" l Note: 'A' "A" A A \0 l c = \012 /* 10 decimal; new line character */ 17

Characters 18

Constants (2.3) l Numeric constants l Character constants l String constants l Constant expressions l Enumeration constants 19

Integer Constants l Decimal numbers 123487 l Octal: starts with 0 (zero) 0654 l Hexadecimal: starts with 0x or 0X 0x4Ab2, 0X1234 l long int: suffixed by L or l 7L, 106l l unsigned int: suffixed by U or u 8U, 127u 20

Floating-point Constants 15.75 1.575E1 /* = 15.75 */ 1575e-2 /* = 15.75 */ -2.5e-3 /* = -0.0025 */ 25E-4 /* = 0.0025 */ l If there is no suffix, the type is considered double (8 bytes). l To specify float (4 bytes), use suffix F or f. l To specify long double (12 or 16 bytes), use suffix L or l. 100.0L /* long double */ 100.0F /* float */ l You can omit the integer portion of the floating-point constant..0075e2 0.075e1.075e1 75e-2 21

Numeric Constants l 2010 l 100000 l 729L or 729l l 2010U or 2010u l 20628UL or 20628ul l 24.7 or 1e-2 l 24.7F or 24.7f l 24.7L or 24.7l l 037 l 0x1f, 0X1f, 0x1F l 0XFUL l int l taken as long if 16-bit int l long (int) l unsigned l unsigned long l double l float l long double l octal (= 31 decimal) l hexadecimal (= 31) l What is this? 22

Character Constants 'x' '2' '\0' l letter x l numeric value 50 l NULL char, value 0 #define NEW_LINE '\012 l octal, 10 in decimal #define SPACE '\x20' l hex, 32 in decimal 23

Escape Sequences 24

String Constants "hello, world\n" "" /* empty string */ \" /* double quote character */ "hello, " " world" same as "hello, world" l concatenated at compile time l useful for splitting up long strings across several source lines. 25

Constant Expressions l Expressions that involve only constants. l Evaluated during compilation. #define MAXLINE 1000 char line[maxline+1]; #define LEAP 1 /* in leap years */ int days[31+28+leap+31+30+31+30+31+31+30+31+30+31]; 26

Enumeration Constants enum boolean { NO, YES }; l The first name in an enum has value 0, the next 1, and so on, unless explicit values are specified. enum colours { black, white, red, blue, green }; enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', VTAB = '\v', RETURN = '\r' }; l If not all values are specified, unspecified values continue the progression from the last specified value. enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; /* FEB = 2, MAR = 3, etc. */ 27

Limits l File limits.h provides several constants char CHAR_BIT, CHAR_MIN, CHAR_MAX, SCHAR_MIN, int INT_MIN, INT_MAX, UINT_MAX long LONG_MIN, l You can find FLOAT_MIN, DOUBLE_MIN, in <float.h> 28

Declarations (2.4) l All variables must be declared before use l A variable may also be initialized in its declaration. char esc = '\\'; int i = 0; int limit = MAXLINE+1; float eps = 1.0e-5; 29

Qualifier const l Indicates that the value of a variable will not be changed. l For an array: the elements will not be altered. const double e = 2.71828182845905; const char msg[] = "warning: "; l Used with array arguments, to indicate that the function does not change that array. int strlen( const char[] ); 30

Arithmetic Operators (2.5) + * / % Examples: abc = x + y * z; j = a % i; ++x; x++; x += 5; /* x = x + 5; */ y /= z; /* y = y / z; */ 31

Precedence and Associativity (Pg 53) 32

Type Conversion (2.7) l float f; int i; What is the type of f+i? l General rule: convert a narrower operand into a wider one without losing information. l So i is converted to float before the addition. l char may be freely used in arithmetic expressions. /* lower: convert c to lower case; ASCII only */ int lower(int c) { if (c >= 'A' && c <= 'Z') return c 'A' + 'a'; else return c; } 33

Arithmetic Conversion: Examples int int double double int double int double double int a=5, b=2, c; double x, y = 2; x = a/b; // x = 2.0 c = a/b; // c = 2 x = a/y; // x = 2.5 c = a/y; // c = 2 34

More Examples l 17 / 5 3 l 17.0 / 5 3.4 l 9 / 2 / 3.0 / 4 9 / 2 = 4 4 / 3.0 = 1.333 1.333 / 4 = 0.333 35

Type Conversion: More Rules l Conversions take place across assignments; the value of the right side is converted to the type of the left, which is the type of the result. l Example: int i; float f = 7, g = 2; i = f / g; l float to int causes truncation of any fractional part. l Example: float f, g = 2.7; int i = 5; f = i; /* f = 5.0 */ i = g; /* i = 2 */ 36

Type Conversion: Even More Rules l Longer integers are converted to shorter ones or to chars by dropping the excess high-order bits. int i; char c; i = c; c = i; /* c unchanged */ int i; char c; c = i; i = c; /* i may be changed */ 37

Casting int A = 9, B = 2; double x; x = A / B; /* x is 4.0 */ x = A / (double)b; /* x is 4.5 */ int n; sqrt(double(n)) Doesn t change the value of B, just changes the type to double l The cast operator has the same high precedence as other unary operators. 38

Increment and Decrement Operators (2.8) l ++ or -- l Placing in front: incrementing or decrementing occurs BEFORE value assigned k = ++i; i = i + 1; k = i; i = 2 and k = 1 k =--i; l Placing after: occurs AFTER value assigned 3 3 i = 2 and k = 1 i = i - 1; k = i; 1 1 k = i++; k = i; i = i + 1; 2 3 k = i--; k = i; i = i - 1; 2 1 39

Relational and Logic Operators (2.6) l Relational operators: > >= < <= ==!= l Logical operators:! && l Evaluation stops as soon as the truth or falsehood of the result is known. 40

Boolean Expressions l 0 is False l Anything else is True l Write if (!valid) instead of if (valid == 0) 41

Bitwise Operators (2.9) (bitwise.c) l They work on individual bits & : Bitwise AND : Bitwise OR ^ : Bitwise exclusive OR ~ : Bitwise complement l Useful when each bit has a different meaning l Handy when memory was at a premium 42

Bit Shifting (shifting.c) l x<<y means shift x to the left y times. l equivalent to multiplication by 2 y l x>>y means shift x to the right y bits. l equivalent to division by 2 y 43

Right Shifting l It could be logical (0) or arithmetic (signed) l If unsigned, 0; if signed undefined in C unsigned int i = 714; 357 178 89 44 22 11 5 2 1 0 l What if i = -714? -357-178 -89... -3-2 -1-1 -1-1 44