Lecture 11: Files & Arrays B Burlingame 18 November 2015.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
UNIT 15 File Processing.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
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.
CSE1301 Computer Programming: Lecture 19 File I/O
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
File Handling Spring 2013Programming and Data Structure1.
Chapter 18 I/O in C.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
File IO and command line input CSE 2451 Rong Shi.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
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.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
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.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
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 13: Arrays, Pointers, Code examples B Burlingame 2 Dec 2015.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Files A collection of related data treated as a unit. Two types Text
Lecture 7: Arrays BJ Furman 06OCT2012. The Plan for Today Announcements Review of variables and memory Arrays  What is an array?  How do you declare.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
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 6: More Decisions & Arrays B Burlingame 9 March 2016.
Lecture 11: Pointers B Burlingame 13 Apr Announcements Rest of semester  Homework Remaining homework can be done in pairs, turn in one paper with.
Chapter 7 Text Input/Output Objectives
ECE Application Programming
Chapter 7 Text Input/Output Objectives
ECE Application Programming
Chapter 7 Text Input/Output Objectives
Lecture 8: Variable Scope & Working with Files
File Access (7.5) CSE 2031 Fall July 2018.
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)
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
Lecture 11: Strings B Burlingame 11 April 2018.
Lecture 10: Strings B Burlingame 4 April 2018.
Computer Programming Lecture 15 Text File I/O
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:
Lecture 8b: Strings BJ Furman 15OCT2012.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
File Input and Output.
Programming in C Input / Output.
Module 12 Input and Output
EECE.2160 ECE Application Programming
CSc 352 File I/O Saumya Debray Dept. of Computer Science
File I/O We are used to reading from and writing to the terminal:
Files Chapter 8.
Presentation transcript:

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