Download presentation
Presentation is loading. Please wait.
Published byHeather Simpson Modified over 6 years ago
1
Lecture 8: Variable Scope & Working with Files
B Burlingame 18 October 2017
2
Announcements Midterm this week Open notes, open book, a few websites
cplusplus.com ME30.org arduino.cc Canvas Read chapters 10, 15
3
Learning Objectives Discuss the importance of style in code
Define scope and variable duration Introduce the concept of files and file I/O
4
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
5
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())
6
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:
7
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:
8
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
9
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
10
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
11
#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
12
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’
13
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.
14
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.
15
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.
16
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"); }
17
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
18
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
19
References Modular Programming in C math.h
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.