Lecture 11: Files & Arrays B Burlingame 18 November 2015
Announcements Homework #5 due Homework #6 due next week Exams available after class Lab 9 & 10 due in lab this week Arduino not needed in lab
Midterm Results Mean80.29 Median84 Mode85 Std Dev14.97 Min33 Max101 Add 5 to the circled score to see calculate your grade
What is an Array? So far we've dealt with scalar variables contain just one value Arrays are collections of data of the same type that occupy contiguous memory locations Individual values in the collection are called elements of the array Need to declare before use: #include int main() { int i=0; double test[4] = {0}; test[0]=95.5; test[1]=74.0; test[2]=88.5; test[3]=91.0; for(i=0; i<4; i++) { printf("test[%d]=%lf",i,test[i]); 0x%p\n",&test[i]); } return 0; } Format (1D array) type array_name [num_elements]; Ex. Array of 4 doubles named, 'test'
What is an array? - 2 int nums [10]; 10 element array of integers Element no. 3 is accessed by: nums [2] because indexing begins at 0
Accessing Array Elements Individual elements of an array are accessed by their index number ** Important Note** Array indexing starts at zero (take note of this, it is easy to forget!) char test[4]; the first element is test [0] the fourth element is test [3] #include int main() { int i=0; doube test[4]={0}; test[0]=95.5; test[1]=74.0; test[2]=82.75; test[3]=91.5; for(i=0; i<4; i++) { printf("test[%d]=%lf",i,test[i]); 0x%p\n",&test[i]); } return 0; } Be careful! The C compiler may not stop you from indexing beyond the boundary of your array. (What could happen?) What is test[4]? array_practice2.c
Initializing Array Elements Use braces to enclose the elements Separate elements by commas Can set number of elements in declaration: Explicit: int nums[5] Implicit: int imp[ ] = {1, 2}; Read from the keyboard Ex. array_practice3.c Note addresses Ex. array_practice4.c Read from the keyboard /* array_practice3.c */ #include int main() { int i=0; int nums[5]={0,1,2,3,4}; for(i=0; i<5; i++) { printf("nums[%d]=%d",i,nums[i]); 0x%p\n",&nums[i]); } return 0; }
Strings By convention, strings in C are a null terminated array of characters There is no intrinsic string datatype Null equals character value 0 i.e. char z = 0; z has a null character written \0 Declaration: char string[] = “Hello world”; Stored: Hello World\0 (ie 12 characters) All string handling expects this
Working with strings Much like working with arrays Many helper routines in string.h strcmp – tests strings for equivalence strcat – concatenates two strings strstr – locates a string within a string Etc. char string[] = “Hello World”; for( int i = 0; string[i] != 0 ; ++i ) { if( string[i] >= ‘A’ && string[i] <= ‘Z’ ) { string[i] = string[i] + (97 – 65); }
Data Streams Data ‘stream’ “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 See reference:
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:
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
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
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
Example #include int main(void) { FILE *infile = fopen("c:/temp/data.dat", "r"); // Open the file 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; }
References Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3 rd ed., Springer, New York, p Visited 23OCT Visited 23OCT