180 likes | 334 Views
B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts since most is discussed. Good for handout, bad for lectures. B Smith: Rate:2/4 More examples needed, fewer words. B Smith:
E N D
B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts since most is discussed. Good for handout, bad for lectures. B Smith: Rate:2/4 More examples needed, fewer words. B Smith: Sp06: rate 2.5 Worked mostly from examples 11.1 and 11.2. Need better examples. B Smith: 4/13/2005 9:54 AM: Rate: 3, low discussion, implement, “Your turn…” Time: 50 minutes C File Processing - I Math 130
Overview • C Functions to Open and Close Streams • Declaring, Opening, and Closing Files • Reading and Writing Files • Example
B Smith: In C a stream is referred to as a FILE. See attached notes. Opening a File • We have been working with programs that have • read from the “standard input” (the keyboard) • written to the “standard output” (the monitor) • How can we access a file which is not already “connected” to the program? • File processing is performed using a FILE structure/data-type. First you must declare an instance of the FILE structure. Examples: FILE* inFile; FILE* prices; FILE* fp;
Opening a File • Use fopen() to open a file • fopen() takes an external name such as “proj01.c” as an argument • fopen() returns an internal file name for use in subsequent reads and writes to the file • this “handle” is a file pointer returned from fopen() //prototype FILE *fopen(char* FileName, char *Mode); FILE *fp; fp = fopen(“proj01.c”, “r”);
fopen() • The file pointer returned from fopen() points to a file structure • A file structure contains file details such as • buffer location • current character position in the buffer • whether the file is being read or written FILE *fp; fp = fopen(“proj01.c”, “r”);
fopen() • The first argument of fopen is the name of the file, taken as a character string • The second argument is the “mode,” • used to indicate how the file is to be used FILE *fp; fp = fopen(“proj01.c”, “r”);
fopen() • The files opened by fopen() will generally be read, written, or appended • allowed modes reflect this • mode r: read • mode w: write • mode a: append, or add to • file name and mode should be enclosed in double quotes FILE *fp; fp = fopen(“proj01.c”, “r”);
pgm 11.1 from Bronson textbook #include <stdlib.h> #include <stdio.h> int main() { FILE *inFile; char fileName[13]; printf("\nEnter a file name: "); gets(fileName); inFile = fopen(fileName,"r"); /* open the file */ if (inFile == NULL) { printf("\nThe file cannot be opened."); printf("\nPlease check that the file currently exists."); exit(1); /* all open streams are closed */ } printf("\nThe file has been successfully opened for reading"); return 0; }
Opening a File for Writing: • This creates a new file • makes the file available for output from the function opening the file • if a file with the same name exists, the old file is erased outFile = fopen(“prices.bnd”,”w”);
pgm 11.2 – Writing a File example #include <stdlib.h> #include <stdio.h> int main() { int i; FILE *outFile; /* FILE declaration */ float price[] = {39.95,3.22,1.03}; /* a list of prices */ char *descrip[] = { "Batteries", /* a list of */ "Bulbs", /* descriptions */ "Fuses"}; outFile = fopen("prices.txt","w"); /* open the file */ if (outFile == NULL) { printf("\nFailed to open the file.\n"); exit(1); } for(i = 0; i < 3; ++i) fprintf(outFile,"%-9s %5.2f\n",descrip[i],price[i]); fclose(outFile); return 0; } system(“start notepad.exe prices.txt”); //to view file
Appending To a File • This makes an existing file available for data to be added to end of file • If the file opened for appending does not exist, a new file is created • This new file is available to receive output from the program • In append mode, data is written to the end of the file • NB: in write mode, data is written starting at the beginning outFile = fopen(“prices.bnd”,”a”);
Reading from a file • Open the file and save the returned pointer • inFile = fopen(“sales.dat”,”r”); • Check for existence of file • if (inFile == NULL) ... • requests to open a nonexistent file will return a NULL address • Read the data using functions similar to scanf(), gets(), and getchar()
Bailing Out • Errors should be communicated back to the OS • By convention, this is done with exit(1) or exit(0) • Errors are also typically reported back to the user • Conventionally, exit will return • a value of 0 for success • a nonzero value to indicate failue • exit calls fclose for each open output file
Closing a File • Use fclose() to close the files you’ve opened • There is a limit to the maximum number of files you can have open • Use the same internal pointer name to close the file • Open files are normally closed automatically by the operating system upon exit
B Smith: Not clear here what’s a proto and what’s a function example! Writing to Files • These functions are almost identical to those used for displaying to a monitor fputc(c, filename)Write a single character to a file fputs(string, filename)Write a string to the file fprintf(filename, “format”, args)Write the values of the arguments to the file according to the format string fputc(‘z’, outFile);Write a ‘z’ to the file fputs(“Nemo was a fish”, outFile)Write the string to the file fprintf(outFile, “%s %d”, descrip, price)
Reading Files • Very similar to reading data from the keyboard • all detect EOF. • fgetc() and fscanf() return EOF when the marker is detected • fgets() returns a NULL when it detects the end of a file fgetc(filename) Read a single character from the file fgets(stringname,n, filename) Read n-1 characters from the file and store in stringname fscanf(filename, “format”, &args) Read values for the listed arguments fgetc(infile);// Read the next character from the file fgets(message, 10, inFile)//Read file until: 9 characters, OR \n, OR EOF fscanf(inFile, “%f”, &price) //Read a floating point number
B Smith: Not a great example since it uses the same field names! The more logical thing to do would be to read a new file with fields chosen by the user! Reading data from a file #include <stdlib.h> #include <stdio.h> int main() { char descrip[10]; float price; FILE *inFile; inFile = fopen("prices.txt","r"); if (inFile == NULL) { printf("\nFailed to open the file.\n"); exit(1); } while (fscanf(inFile,"%s %f",descrip,&price) != EOF){ printf("%-9s %5.2f\n",descrip,price); } fclose(inFile); return 0; }