1 / 23

IPC144

Week 10 – Lesson 2 Working with Files ( IPC144 Subject Notes pages 83 – 93 ). IPC144. Agenda. Purpose for using Files Operations: Reading from Files Writing to Files Read / Write, Write / Read operations Usefulness of Arrays with File Operations Examples / Reality Checks….

elainew
Download Presentation

IPC144

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Week 10 – Lesson 2Working with Files ( IPC144 Subject Notespages 83 – 93 ) IPC144

  2. Agenda Purpose for using Files Operations: 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 readsdata for purpose… or … Program storesdata for future use… Program readsdata and processesdata into report… Program reads data, modifies data and storesdata 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 onlyw - write from onlya - 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 representsa record (containsrelated fields)…. Each column representsa field. Fields are separatedby a comma…

  13. An Example #include<stdio.h> #define NAME_SIZE 80 + 1 #define TITLE_SIZE 40 + 1 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 40 + 1 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 /* Contined from previous page … */ do { printf ("Enter Name: "); scanf ("%[^\n]", employeeName); clearInput(); printf ("Enter age: "); scanf ("%d", &age); clearInput(); printf ("Enter job title: "); scanf ("%[^\n]", employeeTitle); clearInput(); fprintf (fpout, "%s,%d,%s\n", employeeName, age, employeeTitle); printf ("Go again? [y/n]: "); scanf (" %c", &again); clearInput(); }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:

More Related