230 likes | 247 Views
Learn how to read from and write to files in C programming, using functions like fprintf() and fscanf(). Explore file operations and common tasks for file manipulation.
E N D
Week 10 – Lesson 2Working with Files ( IPC144 Subject Notespages 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…
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…
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)…
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…
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
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…
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
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…
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…
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…
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…
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 */
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 */
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!!!!!
Writing Data to Files • Writing to files is similar (easier)See next slide for fprintf function / examples…
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…
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…
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 … */
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 */
Practice • REALITY CHECK – Week 10 Lesson 2 • Question #1 • Question #2
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...
Additional Resources Here are some Related-Links for Interest Only: