Presentation is loading. Please wait.

Presentation is loading. Please wait.

IPC144 Week 10 – Lesson 2 Working with Files

Similar presentations


Presentation on theme: "IPC144 Week 10 – Lesson 2 Working with Files"— Presentation transcript:

1 IPC144 Week 10 – Lesson 2 Working with Files
( IPC144 Subject Notes pages 83 – 93 )

2 Agenda Purpose for using Files Operations: Examples / Reality Checks…
Reading from Files Writing to Files Read / Write, Write / Read operations Usefulness of Arrays with File Operations Examples / Reality Checks…

3 Purpose of Files So far, we have learned to store values into variables or elements of an array. The problem with this method, is that any information is lost when the program ends. Since data stored in files are considered a more permanent form of storage, it is common for programs to read / modify / write data to files…

4 Purpose of Files Common File Operations:
Program reads data for purpose… or … Program stores data for future use… Program reads data and processes data into report… Program reads data, modifies data and stores data into the same file… (more complex)…

5 How is it Done? The stdio.h library contains two functions:
fprintf() - write data to a file fscanf() - reads data from a file It is a “convenient” solution since fprintf() and fscanf() are easily identified with the printf() and scanf() functions we have already used… … we just need to learn a few new things…

6 How is it Done? The stdio.h library also sets up the name FILE
(by definition at the start of main) to allow a “connection” to the data file and the C program. A “pointer” is used to become the “Bridge” to access data to / from the file and the C program… pointer pointer C Program C Program

7 How is it Done? Reading From a File - STEPS:
Define a POINTER that points to a FILE (eg. FILE *fp_in; /* when declaring variables… */ ) Open the file for reading, and check to see if file exists (if it doesn’t exist – display an error message) Run a loop while fscanf() successfully scans in each line data to either: Load appropriate data into elements of array(s) - Perform tasks for each line (eg. accumulating totals, etc…) When finished all operations, close the file…

8 Reading Data From Files
fopen() function Fopen() function is used to open a file Usage: fopen( “filename”, “operation”); Where operation can be: r - read from only w - write from only a - wtrite to bottom of file

9 Reading Data From Files
fopen() function NOTE: If the fopen() function was NOT able to open the file for reading or writing, it will return an exit status of zero, or an exit status of 1 if it was successful… Therefore, you can use logic to determine to proceed with file operations, or display an error message…

10 Reading Data From Files
fscanf(filepointer, “format specifier”, variable(s)) File pointer that was defined with FILE is bridge between file and program… Format specifier indicates type of data, and delimiters (note: end of record is normally indicated by new-line (\n)… fscanf() will continue to scan data as long as it Returns the correct number of variables it stored data into – fscanf() will abort otherwise…

11 Reading Data From Files
fclose() function It is important to close the file connect prior to terminating the C program Why? Is could cause locked records, loss of data, etc…

12 An Example Example for comma-delimited file:
cat employee.dat Murray Saul,44,Professor David Ward,63,Professor Evan Weaver,56,Chair Hassan Assiri,55,ACS Manager Chris Jankul,65,professor Bart Simpson,10,under achiever one two,3,four five six Each row represents a record (contains related fields)…. Each column represents a field. Fields are separated by a comma…

13 An Example #include<stdio.h> #define NAME_SIZE 80 + 1
#define TITLE_SIZE main() { int age, total = 0, count = 0; char employeeName[NAME_SIZE]; char employeeTitle[TITLE_SIZE]; FILE *fpin; fpin = fopen("employee.dat", "r"); if ( fpin == NULL) printf ("Error: the data file does not exist\n\n"); exit (1); } /* Continued on next page */

14 An Example /* continued from previous page …. */ else
while( fscanf(fpin, "%[^,],%d,%[^\n]\n", employeeName, &age, employeeTitle) == 3) { total += age; count += 1; } printf ("The average age is: %d\n\n", total / count); fclose(fpin); } /* end of main program */

15 A Word of Caution! In previous slide containing code: while( fscanf(fpin, "%[^,],%d,%[^\n]\n", employeeName, &age, employeeTitle) == 3 Notice the format specificer "%[^,],%d,%[^\n]\n“ For strings, we read to comma field delimiter, but we do NOT include the comma delimiter as the string – BE CAREFUL TO DO THIS!!!!!

16 Writing Data to Files Writing to files is similar (easier) See next slide for fprintf function / examples…

17 How is it Done? Writing to a File - STEPS:
Define a POINTER that points to a FILE (eg. FILE *fp_in; /* when declaring variables… */ ) Open the file for reading, and check to see if file exists (if it doesn’t exist – display an error message) Run a loop while fprintf() write one record (line) at a time…. NOTE: - Separate data with a delimited (i.e. symbol like “,” or “;” etc…) - End record with newline character (i.e. “\n” ) When finished all operations, close the file…

18 Writing Data to Files fprintf(filepointer, “format specifier”, variable(s)) File pointer that was defined with FILE is bridge between file and program… Format specifier indicates type of data, and delimiters (note: end of record is normally indicated by new-line (\n)… Variables are specified to temporarily store values. Note: use of arrays are handy to use here…

19 An Example #include<stdio.h> #define NAME_SIZE 80 + 1
#define TITLE_SIZE void clearInput(void); main() { int age; char employeeName[NAME_SIZE]; char employeeTitle[TITLE_SIZE]; char again; FILE *fpout; fpout = fopen("employee.dat", "a"); /* Contined on next page … */

20 An Example do { printf ("Enter Name: ");
/* Contined from previous page … */ do { printf ("Enter Name: "); scanf ("%[^\n]", employeeName); clearInput(); printf ("Enter age: "); scanf ("%d", &age); printf ("Enter job title: "); scanf ("%[^\n]", employeeTitle); fprintf (fpout, "%s,%d,%s\n", employeeName, age, employeeTitle); printf ("Go again? [y/n]: "); scanf (" %c", &again); }while ( toupper(again) == 'Y'); fclose(fpout); } /* end of main program */ void clearInput(void){ while(getchar() != '\n') ; } /* end of clearInput() function */

21 Practice REALITY CHECK – Week 10 Lesson 2 Question #1 Question #2

22 Homework For your assignment #3, Write a C program that reads, and
displays the contents of price.dat and trip.dat files… Write another C program that reads, user input and stores the contents on a file called report.txt (delimited by commas)… IF YOU CAN DO THIS BY THIS THURSDAY, YOU ARE IN GOOD SHAPE...

23 Additional Resources Here are some Related-Links for Interest Only:


Download ppt "IPC144 Week 10 – Lesson 2 Working with Files"

Similar presentations


Ads by Google