Lecture 8: Variable Scope & Working with Files

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
UNIT 15 File Processing.
1 ICS103 Programming in C Lecture 8: Data Files. 2 Outline Why data files? Declaring FILE pointer variables Opening data files for input/output Scanning.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
Guide To UNIX Using Linux Third Edition
CSE1301 Computer Programming: Lecture 19 File I/O
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
V-1 University of Washington Computer Programming I File Input/Output © 2000 UW CSE.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
A First Book of ANSI C Fourth Edition Chapter 10 Data Files.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 8: Functions, File IO.
Chapter 18 I/O in C.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
File IO and command line input CSE 2451 Rong Shi.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
Lecture 8a: File I/O BJ Furman 21MAR2011. Learning Objectives Explain what is meant by a data stream Explain the concept of a ‘file’ Open and close files.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
Lecture 10: Peripherals Bryan Burlingame 04 November 2015.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Files A collection of related data treated as a unit. Two types Text
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
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.
Lecture 7: Variable Scope B Burlingame March 16, 2016.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
User-Written Functions
ECE Application Programming
University of Washington Computer Programming I
Chapter 7 Text Input/Output Objectives
Chapter 18 I/O in C.
File I/O.
CS 261 – Recitation 7 Fall 2013 Oregon State University
Plan for the Day: I/O (beyond scanf and printf)
Lecture 7: Modular Programming (functions)
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
Programming in C Input / Output.
CSE1320 Files in C Dr. Sajib Datta
File I/O We are used to reading from and writing to the terminal:
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Chapter 14 - Advanced C Topics
Chapter 18 I/O in C.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
FILE HANDLING IN C.
File Input and Output.
Chapter 18 I/O in C.
Programming in C Input / Output.
1-6 Midterm Review.
Module 12 Input and Output
EECE.2160 ECE Application Programming
Programming Languages and Paradigms
The Three Attributes of an Identifier
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
EECE.2160 ECE Application Programming
ICS103: Programming in C 6: Pointers and Modular Programming
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Chapter 18 I/O in C.
Presentation transcript:

Lecture 8: Variable Scope & Working with Files B Burlingame 18 October 2017

Announcements Midterm this week Open notes, open book, a few websites cplusplus.com ME30.org arduino.cc Canvas Read chapters 10, 15

Learning Objectives Discuss the importance of style in code Define scope and variable duration Introduce the concept of files and file I/O

Data Streams Data ‘stream’ Prior to UNIX UNIX “an ordered series of bytes” (Darnell and Margolis, 1996) Like a 1D array of characters that can flow from your program to a device or file or vice-versa IO involves reading data from or writing data to a stream Prior to UNIX Programmers had to handle all the intricacies and complexities of interfacing to input and output devices, such as card readers, printers, terminals, etc. UNIX Abstracted away the details of IO to the concept of the data stream Established standard data streams: stdin – data coming into your program (usually from the keyboard) stdout – data going out of your program (usually to the display) stderr – for error information going out of your program

File IO Need to first associate a stream with a file or device Three streams are automatically opened and associated with your program: stdin, stdout, stderror Ex. printf() defaults to printing to the display To read from or write to another file stream, you need to declare a pointer to a data structure called FILE This pointer is used to read from, write to, or close the stream Use IO functions for file operations (like fprintf())

Opening a File - 1 Key steps: Declare a pointer to FILE FILE *fp = NULL; Provides the means to associate a file with a data stream Will be used by other functions such as fprintf() Use fopen() function with a path to the file and a file mode as arguments Ex. Open file_name.txt to be able to read from it fp = fopen(“file_name.txt”, “r”); fopen() returns a pointer to the file fp stores the pointer to the file, file_name.txt “r” opens the file for reading from Can also open a file to write to it or append to it fp is the name of the pointer to FILE See the file file_I_O.c See reference: http://www.cppreference.com/wiki/c/io/fopen

Source: http://www.cppreference.com/wiki/c/io/fopen Opening a File - 2 Other modes Good idea to test that the file was opened without error fopen() will return NULL if there is an error opening the file fp = fopen(“file_name.txt”, “r”); if(fp == NULL) { printf("Error: can't open file to read\n"); return 1; } Source: http://www.cppreference.com/wiki/c/io/fopen

Working with a file File functions correspond to keyboard functions fprintf( filehandle, “format string”, parameters); Ex: fprintf( outfile, “%d %d\n”, x, y ); Looks and acts like printf, but writes to a file fscanf( filehandle, “format string”, parameters); Ex: fscanf( infile, “%d %d”, &x, &y ); Looks and acts like sscanf, but reads from a file No need for fgets See the file file_I_O.c

Closing a File Function header: int fclose(FILE *fp); Good idea to test the file was closed without error Test the return value of fclose fclose() will return EOF if there is an error closing the file if(fclose(fp) == EOF) { printf("Error closing file\n"); return 1; } It is best practice to close all files that you opened, somewhere in your program See the file file_I_O.c

Arrays and File I/O Arrays are often used with data consisting of many elements Often too tedious to handle I/O by keyboard and monitor File I/O is used instead

#include <stdio. h> int main(void) { FILE #include <stdio.h> int main(void) { FILE *infile = fopen("c:/temp/data.dat", "r"); // Open the file, note the * FILE *outfile = fopen(“c:/temp/out.dat”, “w”); int number = 0; double sum = 0.0; if ( NULL == infile || NULL == outfile ) { // Ensure the files // opened correctly fprintf(stderr, "Error opening data files\n"); // report an error, if return 1; // it didn’t } while ( fscanf(infile, "%d", &number ) != EOF ) { // Read until end of file sum += number; // (EOF) fprintf( outfile, “%d\n”, sum ); // Write the sum to a file if ( fclose(infile) == EOF ) { // close infile fprintf(stderr, “Error closing infile\n”); return 2; if ( fclose(outfile) == EOF ) { return 3; } // close outfile return 0; Example

YES! --> concept of ‘scope’ Identifiers and Scope Identifier The name of a variable, function, label, etc. int my_var1; /* a variable */ pow_table(); /* a function */ start: /* a label */ Question: Does it make a difference where in a program an identifier is declared? YES! --> concept of ‘scope’

Scope of Identifiers Scope of a declaration of an identifier The region of the program that the declaration is active (i.e., can access the variable, function, label, etc.) Five types of scope: Block (“between the { } scope”) Program (global scope) File Function prototype Function Scope refers to the region in the program where the identifier can be referenced.

Scope of Identifiers - Block Scope Block (local) scope A block is a series of statements enclosed in braces { } The identifier scope is active from the point of declaration to the end of the block ( } ) Nested blocks can both declare the same variable name and not interfere ex. from Ch var_scope_block.c scope_nested_blocks.c #include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) double result; result = x * y; return result; Show how this works in ChIDE using var_scope_block.c Show also scope_nested_blocks.c Note: a variable declared in a block that also contains a block (nested block) is active within the contained block, but not vice-versa.

Scope of Identifiers - Program (Global) Scope if declared outside of all functions "Visible" to all functions from point of declaration Visible to functions in other source files Use only when necessary and then very carefully!! ex. from Ch var_scope.c #include <stdio.h> int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) double result; result = x * y; return result; Switch to ChIDE and show a modified version of the program with printf() statements included (var_scope.c) that show variable a is 'visible' throughout the program. Assign a new value in function to show how variable a is accessible and changeable. Beware!! Try to avoid using global variables. The temptation is that the variable is visible to all modules - simple and fast … But, it makes maintenance more difficult. Enables potential conflicts between modules where two programmers working on separate modules might use the same name for different global variables. Can introduce bugs that are hard to find. Any time you see a source file with global variables defined, you need to go through all source files that are part of the program to make sure there are no conflicts. Adds other restrictions like the ANSI standard only guaranteeing that a compliant compiler recognize the first 6 characters of a global variable, and may suspend case sensitivity. Better to pass data directly or via pointers.

Scope of Identifiers - Function Scope Applies only to labels start: * goto start; Active from the beginning to the end of a function Ex. Statement labels in a switch selection structure #include <stdio.h> int main() { int user_sel; /* prompt user for entry */ /* get user entry */ switch( user_sel ) case 1: printf("\n message..."); /* call game function1 here */ break; case 2: /* call game function2 here */ default: printf("Error"); }

Storage Duration How long the identifier exists in memory Static storage class Identifier exists when program execution begins For variables: Storage allocated and variable is initialized once Retains their values throughout the execution of the program #include <stdio.h> void just_count(void); /* proto */ int main() { int i; for(i=0;i<10;i++) just_count(); } return 0; void just_count(void) static int count_a = 0; int count_b = 0; count_a = count_a + 1; count_b = count_b + 1; printf("count_a== %d\n", count_a); printf("count_b== %d\n", count_b); Visible throughout the program as before, except variable a is not visible to functions defined in other source files. Run just_count.c just_count.c

Storage Duration, cont. For functions: function name exists when execution begins For variables with global scope: i.e., declared outside of all functions and uses static keyword "Visible" to all functions from point of declaration in this source file only Keeps data ‘private’ to this file only #include <stdio.h> static int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double x, double y) double result; result = x * y; return result; Visible throughout the program as before, except variable a is not visible to functions defined in other source files

References Modular Programming in C http://www.icosaedro.it/c-modules.html math.h http://www.opengroup.org/onlinepubs/007908799/xsh/math.h.html http://www.cprogramming.com/tutorial/style.html