24-2 perform file i/o using file pointers file * data-type opening and closing files character input...

15

Upload: adelia-king

Post on 21-Jan-2016

239 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
Page 2: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-2

• 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

Page 3: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-3

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.

Page 4: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-4

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.

Page 5: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

/* 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");

Page 6: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

/* 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);}

Page 7: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

After the above program is compiled execution from the Unix prompt:

> more input.dat12345> ./a.outPlease enter an input filename (use path if needed):input.datPlease enter an output filename (use path if needed):output.dat> more output.datAve of 5 numbers = 3.000000>

Page 8: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-8

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.

Page 9: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-9

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 thefile 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.

Page 10: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-10

FILE *fileOut;

fileOut = fopen("output.dat", "w");

The first argument “output.dat” is a string that names thefile 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).

Example:

If an already existing file is opened with mode “w” the old contents are discarded.

Page 11: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-11

FILE *fileOut;

fileOut = fopen("out.dat", "a");

The first argument “out.dat” is a string that names thefile 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).

Example:

Page 12: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

23-12

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.

Mode If the file exists If the file doesn’t exist

“r” Opens the file for reading fopen returns NULL

“w” Opens file for writing and deletes contents

creates a new file

“a” Opens a file for appending (writing at the end of the file)

creates a new file

Page 13: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-13

fprintf function is in <stdio.h>. It is the same as the printf function except that the first argument for fprintf is 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);

Page 14: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-14

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.

Page 15: 24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:

24-15

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.