Programming. Functions and File I/O

Similar documents
Standard File Pointers

CS101 Introduction to computing Function, Scope Rules and Storage class

C programming basics T3-1 -

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

Contents. A Review of C language. Visual C Visual C++ 6.0

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Input / Output Functions

UNIT IV-2. The I/O library functions can be classified into two broad categories:

CE Lecture 11

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

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

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

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

File Access. FILE * fopen(const char *name, const char * mode);

25.2 Opening and Closing a File

Lecture 9: File Processing. Quazi Rahman

M.CS201 Programming language

EM108 Software Development for Engineers

Writing to and reading from files

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

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

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Standard C Library Functions

CSCI 171 Chapter Outlines

C Programming Language

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

HIGH LEVEL FILE PROCESSING

Input/Output and the Operating Systems

Functions in C C Programming and Software Tools

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

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

Lecture 9 - C Functions

CS240: Programming in C

Organization of a file

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

File I/O. Arash Rafiey. November 7, 2017

CSE 230 Intermediate Programming in C and C++ Functions

CSI 402 Lecture 2 Working with Files (Text and Binary)

C File Processing: One-Page Summary

File IO and command line input CSE 2451

Introduction to file management

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Programming Fundamentals

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Engineering program development 7. Edited by Péter Vass

System Software Experiment 1 Lecture 7

Input/Output: Advanced Concepts

MODULE 3: Arrays, Functions and Strings

CS240: Programming in C

Computer Programming Unit v

Advanced C Programming Topics

Lecture 04 FUNCTIONS AND ARRAYS

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Functions. Systems Programming Concepts

PROGRAMMAZIONE I A.A. 2017/2018

Programming & Data Structure

C for C++ Programmers

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

2009 S2 COMP File Operations

Goals of this Lecture

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

Procedural programming with C

C Basics And Concepts Input And Output

EC 413 Computer Organization

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

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

Lecture 04 FUNCTIONS AND ARRAYS

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

C-Refresher: Session 10 Disk IO

Computer Programming: Skills & Concepts (CP) Files in C

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

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

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

File (1A) Young Won Lim 11/25/16

CSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community

A Crash Course in C. Steven Reeves

Ch 11. C File Processing (review)

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

Pointers and File Handling

8. Characters, Strings and Files

UNIX input and output

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

Data File and File Handling

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Continued from previous lecture

Chapter 11 File Processing

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

Chapter 12. Files (reference: Deitel s chap 11) chap8

Transcription:

Programming Functions and File I/O

Summary Functions Definition Declaration Invocation Pass by value vs. pass by reference File I/O Reading Writing Static keyword Global vs. local variables 2

Functions Functions are subprograms that perform some operation How to write a program using functions? Conceptualize how a program can be broken into smaller parts Approach: Break down problem into simpler sub-problems Consider iteration and recursion Minimize transfer of state between functions Writing pseudocode first can help 3

Code Repetition Do NOT copy-paste code! Avoid at all cost! Greater probability of error Difficult to change Unreadable code Functions are the solution: Give some name to actions often repeated Set of instructions that can be invoked whenever is needed Eliminates code repetition Code is more readable, easy to understand and write 4

Function Definitions int main(void) / do stuff / return EXIT_SUCCESS; / success / Already seen some functions, including main()! Functions encapsulate some operation, so code can be re-used by others for example, the abs() or sqrt() function 5

Function Characteristics Reusable code code in sqrt() is reused often Encapsulated code implementation of sqrt() is hidden Can be stored in libraries sqrt() is a built-in function found in the math library Example: clear the screen and write a string Bad choice: repeat the code whenever it is needed Good choice: create a function and invoke it whenever is needed 6

Function Definition /* convert temperatures in Celsius to temperatures in Fahrenheit */ double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; Function definition ignores where it is invoked Receives a double and returns a double Input parameter: paramcel (temperature in Celsius) Returns a value that corresponds to the temperature in Fahrenheit 7

How to Use a Function? #include <stdio.h> double CtoF( double ); /******************************************************************* * Purpose: to convert temperature from Celsius to Fahrenheit *******************************************************************/ int main() double c, f; printf("enter the degree (in Celsius): "); scanf("%lf", &c); f = CtoF(c); printf("temperature (in Fahrenheit) is %lf\n", f); double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 8

Definitions Declaration: double CtoF( double ); Can be declared in.h Invocation (Call): Fahr = CtoF(Cel); In any place Definition: double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 9

Function Declaration Also called function prototype: return_type function_name (parameter_list) double CtoF(double) Declarations describe the function: Return type and function name Type and number of input parameters Doesn t need to have any input parameter or return any value void keyword! Functions in the same scope must have unique declarations 10

Already Known Functions Already known functions printf(), scanf(), sqrt(), sin() C Libraries have plenty of functions that can be used The return type must agree with the function return type WRONG: int val = sqrt(4.0); Input parameters must also agree in number and type to the defined function parameters WRONG: clock_t time = clock(20); 11

Function Invocation int main() f = CtoF(c); 1. Call copies argument c to parameter paramcel 2. Control transfers to function CtoF double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 12

Function Invocation int main() f = CtoF(c); 3. Expression in CtoF is evaluated 4. Value of expression is returned to main double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 13

Observations The parameter paramcel is only defined while the function is executing paramcel cannot be used outside the function The name of the parameter does not need to be the same as the name of the argument However, types must agree 14

Variable Scopes Scope Where a variable is known to exist No variable is known outside of the curly braces (block) that contain it, even if the same name is used! Variables declared inside a function: Called local variables Only know in the function Can only be manipulated inside the function Input parameters Are local variables Initialized with the value (copy) of the actual parameter In different functions a variable with the same name can be defined 15

Functions: Example #include <stdio.h> double GetTemperature(); double CelsiusToFahrenheit( double ); void DisplayResult( double, double ); int main() double TempC, TempF; // Temperature in degrees Celsius // Temperature in degrees Fahrenheit TempC = GetTemperature(); TempF = CelsiusToFahrenheit(TempC); DisplayResult(TempC, TempF); return 0; 16

Functions: Example (cont) double GetTemperature() double Temp; printf("\nplease enter a temperature in degrees Celsius: "); scanf("%lf", &Temp); return Temp; double CelsiusToFahrenheit(double Temp) return (Temp * 1.8 + 32.0); void DisplayResult(double CTemp, double FTemp) printf("original: %5.2f C\n", CTemp); printf("equivalent: %5.2f F\n", FTemp); return; 17

Pass by Value A copy of the argument s value is passed to the called function Changes to the copy do not affect the original variable s value in the caller Disadvantage: when a large data item is an argument, copying data may take considerable resources (execution time and memory) 18

Example: Pass by Value /* C function using pass by value */ void transform( int x ) x = 19; /* Test function for passing by value */ int main() int z = 15; transform( z ); printf("z is now %d\n", z); return 0; 19

Pass by Reference Called function can access and modify the caller s argument data directly Pass-by-reference advantage: good for performance reasons, because reduces the pass-by-value computational and memory overhead Pass-by-reference should be used with care: the called function can corrupt the caller s data Parameter name in the body of the called function actually refers to the original variable in the calling function Reference parameter pass the address (using the & operator) of the variable to be modified & placed after the parameter when the function is invoked 20

Pass by Reference Passing parameters by reference: In the function declaration always use * * declares a reference for a variable: can by any type! Allows to change the content of the variable referred by the function parameter Parameter usage f(int x) x = 12; // changes to variable x: no impact outside the function f(int *x) *x = 12; // changes of variable referred by x: impact outside the function 21

Pass by Reference int val = 10; MyFun(&val); printf( %d,val); void MyFun(int *param) *param = 27; Name Address Value val 0xeffffa90 10 param 0xefffea88 0xefffa90 22

Example: Pass by Reference /* C function using pass by reference */ void transform( int *x ) *x = 19; /* Test function for passing by reference */ int main() int z = 15; transform( &z ); printf("z is now %d\n", z); return 0; 23

Recursion Pseudo-code for the computation factorial if n == 0 then result = 1 else result = n * factorial(n 1) 5! = 5 * 4 * 3 * 2 * 1 = 5 * 4! Recursive call: Function contains an invocation of itself int Factorial(int n) if(n == 0) Base Case: Never Forget! May lead to return 1; infinite recursion else return n * Factorial(n-1); 24

File I/O File: sequence of characters or binary data on disk File I/O always involves three steps: Open the file (fopen) Read or write from/to the file (e.g. fgets/fputs) Close the file (fclose) 25

File I/O: fopen C allows to read data from text/binary files using fopen() FILE* fopen(char name[], char mode[]); FILE is an abstract data structure which holds information about a file Name is the location of the file on the disk (can be anywhere) Mode defines how the file is opened: can be "r"(read-only),"w"(writeonly),"a"(append) among other options fopen returns a pointer to the file stream (FILE *) if the file exists or NULL otherwise stdin, stdout are standard input and output FILE* datatypes stderr corresponds to the standard error output (different from stdout) 26

File I/O: fclose int fclose (FILE* fp) Closes the file stream and releases OS resources Automatically called on all open files when program ends 27

Modes of fopen Write, Read and Append File must exist when opened in read mode If file exists in write mode its contents will be overwritten Append doesn t overwrite contents as in the write mode r - open a text file for reading w - truncate to zero length or create a text file for writing a - (append) open or create text file for writing at end-of-file rb - open binary file for reading wb - truncate to zero length or create a binary file for writing ab - (append) open or create binary file for writing at end-of-file 28

Example: Opening and Closing a File #include <stdio.h> #include <stdlib.h> int main () FILE *inputfp, *outputfp; char outputfile[] = "my_output.txt"; Opening a file for reading inputfp = fopen("my_input.txt", "r"); if (inputfp == NULL) printf("can't open input file my_input.txt!\n"); exit(exit_failure); outputfp = fopen(outputfile, "w"); if (outputfp == NULL) printf("can't open output file %s!\n", outputfile); exit(exit_failure); fclose(inputfp); fclose(outputfp); return EXIT_SUCCESS; Opening a file for writing Closing files! 29

File I/O: getc and fgets int getc(file* fp) Reads a single character from the file stream Returns the character read or EOF on error/end of file char[] fgets (char line [], int maxlen, FILE* fp) Reads a single line (up to maxlen characters) from the input file stream (including line break) Returns a pointer to the character array that stores the line (read-only) Returns NULL if end of stream or in case of error 30

File I/O: putc, fputs, fscanf, fprintf int putc( int c,file* fp) Writes a single character c to the output stream Returns the character written or EOF on error int fputs (char line [], FILE* fp) Writes a single line to the output stream Returns zero on success, EOF otherwise int fscanf (FILE* fp, char format [],.) Similar to scanf and sscanf Reads items from input stream fp int fprintf(file* fp, char format [],.) Similar to printf 31

Non-Persistent Storage If a variable declaration is executed multiple times, is new memory for the variable allocated each time? For normal variables yes int f ( void ) int temporary;... Each time f() is called, new memory is allocated for temporary Each time f() terminates, the memory is deallocated that instance of temporary disappears Allocation and deallocation takes time and effort 32

Persistent Storage: static If a variable declaration is executed multiple times, is new memory for the variable allocated each time? For static variables the answer is no! Memory is allocated once at the first use of the variable and then reused int f ( void ) static int persistent;... The first time f() is called, new memory is allocated for persistent Every next call to f() reuses that memory potentially using values that earlier calls to f() left behind 33

Why Use Static Storage? Avoid overhead of allocating, initializing, deallocating memory with each function call Maintain some state information over multiple calls to the function int f( void ) /* count number of times f has been called */ static int num_calls = 0;... num_calls++; return; 34

Global vs Local Variables Variables declared inside each function (including main) are local variables Even if the same name is used! Memory reserved for each variable is deallocated at the end of the function Global variables: variables external to every function that is recognized by every function If a function changes the global variable contents, its stay allocated and accessible even if the function ends Global variable declaration statements should appear before any function definition Right at the beginning of the file 35

Example: Global Variables // declare global variable int g_nmode = 1; void dosomething() g_nmode = 2; int main() g_nmode = 1; dosomething(); // Programmer expects g_nmode to be 1 // But dosomething changed it to 2! if (g_nmode == 1) printf("no threat detected.\n ); else printf("launching nuclear missiles... ); 36 return 0;

Warning: Global Variables! An alteration in the value of a global variable within a given function may have impact over all other functions Global variable may change unexpectedly, resulting in a subtle programming error which can be extremely difficult to detect Conclusion: AVOID ITS USE!!! 37

To Review Marques de Sá Capítulo 4 Capítulo 10 (até ao 10.4) Damas Capítulo 5 Capítulo 10 Kernighan and Ritchie Chapter 4 Chapter 7 38