1 / 15

Perform File I/O with FILE Pointers

Learn how to manage files using FILE pointers, perform operations like opening, closing files, character and string input/output. Implement a program to compute the average value of a list of integers.

evelynhall
Download Presentation

Perform File I/O with FILE Pointers

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. Lecture 24

  2. What will I learn in this lecture? • Perform File I/O using file pointers • FILE * data-type • Opening and closing files • Character Input and Output • String Input and Output • Related Chapter: ABC 11.3, 11.4

  3. File I/O So far, we have seen that one way to manipulate files in a program is to redirect the standard input and output. E.g. in UNIX command line ./a.out < input.dat > output.dat We redirect standard input as the file, input.dat (not a keyboard) And standard output as the file, output.dat(not screen) This method works for one input file and one output file. In this lecture we will consider an alternative, using FILE pointers.

  4. Example - Compute the Average Value of a File of Integers 1. Problem Definition Write a program that computes the average of a list of integers. The program should prompt the user for the name of both the input and output files and then read the values from the input file and print the average value in the output file. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = String naming the file of integers to be read and a string naming the output file. Also, the integers in the file. Output = The average value is written to the output file.

  5. Example - Computing the Average Value /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count = 0; /* fileptrIn and fileptrOut are variables of type “FILE *” */ FILE * fileptrIn, * fileptrOut; char filenameIn[100],filenameOut[100]; printf("Please enter an input filename (use path if needed):"); scanf("%s",filenameIn); printf("Please enter an output filename (use path if needed):"); scanf("%s",filenameOut); /* open files to read “r” and write “w” */ fileptrIn = fopen(filenameIn, "r"); fileptrOut = fopen(filenameOut, "w");

  6. Example - Computing the Average Value /* check to see if program found file */ if ((fileptrIn == NULL) || (fileptrOut == NULL)) { printf("file not opened, program terminated.\n"); return; } /* fscanf */ while( EOF != fscanf(fileptrIn,"%i", &value)) { total += value; ++count; } /* end of while loop */ /* Write the average value to the file. fprintf */ fprintf(fileptrOut, "Ave of %i numbers = %f \n" ,count,total/(double)count); fclose(fileptrIn); fclose(fileptrOut); }

  7. Execution - How it Works After the above program is compiled execution from the Unix prompt: > more input.dat 1 2 3 4 5 > ./a.out Please enter an input filename (use path if needed):input.dat Please enter an output filename (use path if needed):output.dat > more output.dat Ave of 5 numbers = 3.000000 >

  8. FILE - data-type FILE (all caps) is a structure defined in <stdio.h>.In CS101 we will only use this data type in the declaration of pointer variables. Examples: FILE *ptrFileIn; FILE *ptrFileOut; declares ptrFileIn and ptrFileOut as pointer variables. They both “point” to values of data-type FILE. We must have #include <stdio.h> in our source file to use FILE pointers.

  9. fopen To use fscanf and fprintf you must first open a file, we use the library function fopen (defined in <stdio.h>.) For example, to open the file input.dat for reading, we write FILE *fileIn; fileIn = fopen("infile.dat", "r"); The first argument “infile.dat” is a string that names the file to be read. The second argument the mode, “ r ”, stands for “reading” mode only. If the file cannot be opened, fopen returns NULL. (e.g. file doesn’t exit) fopen returns a pointer to the file(in this case infile.dat). The file pointer is the handle to the file, once the file is opened with fopen a programmer can manipulate the file with this pointer.

  10. fopen Example: FILE *fileOut; fileOut = fopen("output.dat", "w"); The first argument “output.dat” is a string that names the file to be read. The second argument the mode, “ w ”, stands for “write” mode only. fopen returns a pointer to the file(in this case (output.dat). If an already existing file is opened with mode “w” the old contents are discarded.

  11. fopen Example: FILE *fileOut; fileOut = fopen("out.dat", "a"); The first argument “out.dat” is a string that names the file the you to which you want to write . The writing takes place at the end of the original file. If the file out.dat already exists it will not be destroyed as in the case for “w” mode. fopen returns a pointer to the file(in this case (out.dat).

  12. fopen - mode When we open a file such as infile.dat we need to specify in advance whether we want to read from the file, write to the file, append to the file. A file can be opened in one mode, closed and then reopened in another mode.

  13. fprintf fprintffunction is in<stdio.h>. It is the same as theprintffunction except that the first argument for fprintfis a file pointer: fprintf(ptrFileOut, ctrlString, expression(s)); where ctrlString contains the format specifiers, and expression(s) can contain one or more variable names and constants. Examples: fprintf(ptrFileOut, "%i ", intVlaue); fprintf(ptrFileOut, "%f ", a + 5.0 * b);

  14. fscanf fscanf function is also in <stdio.h>. It is the same as the scanf function except that the first argument for fscanf is a file pointer; i.e., fscanf(ptrFileIn, ctrlString,address(es)); Examples - fscanf(ptrFileIn, "%lf", &dataValue); fscanf(ptrFileIn, "%c%s%i", &ch, str, &num); - returns an int value equal to number of items successfully read from file (e.g., 0, 1, 2, 3 in last example), or returns the value of EOF if end of file is encountered before any values are read in. Thus, fscanf can be used as an input check just like scanf.

  15. fclose To close a file that is opened, you must use fclose. The function expects one argument, a pointer to FILE. The function fclose returns zero if it successfully closes the file and EOF otherwise.(e.g file doesn’t exist) FILE *fileIn; fileIn = fopen("infile.dat", "r"); … fclose(fileIn); When a program terminates, all open files are automatically closed.

More Related