Sie sind auf Seite 1von 47

UT D

CS1325 - Unit 9.1:


File Processing

UT D

Introduction

File Processing
Introduction
File processing in C is a big subject, and unfortunately we
dont have time to cover more than the basics right now.
In C, we can read and write sequential files (i.e., files
that are written to or read from in a sequential manner,
generally text files, which may be interpreted according
to the ASCII table), and random access files (which are
generally considered as collections of raw bytes). There
are several functions that support both of these.

Because of time constraints, were just going to consider


one aspect of file I/O in C: reading and writing text
(sequential) files.
3

C views each file simply as a sequential stream of bytes


(Fig. 11.1).
When a file is opened, a stream is associated with it.
Streams provide communication channels between files and
programs.

Each file ends either with an end-of-file marker or at a


specific byte number recorded in a system-maintained,
administrative data structure.
Three files and their associated streams are automatically
opened when program execution beginsthe standard
input, the standard output and the standard error.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

File Processing

In general, file processing in C consists of three steps:


opening a file,
using the file,
closing the file.

UT D

Opening a File
Book 11.3.1, 11.3.2

File Processing
Files and Streams

When we open a file, a pointer to a FILE structure (defined in


<stdio.h>) is returned that contains information used to
process the file.
In some systems, this structure includes a file descriptor, i.e., an index into
an operating system array called the open file table.
Each array element contains a file control block (FCB) that the operating
system uses to administer a particular file.

Each file ends either with an end-of-file marker or at a specific


byte number recorded in a system-maintained, administrative
data structure.

The standard input, standard output and standard error are


manipulated using file pointers stdin, stdout and stderr.
7

File Processing
Using a File File Structures

When a file is opened, several supporting data structures are


created, including a File Structure and a File Control
Block for that file in the Open File Table. A pointer to the
File Structure is returned by the fopen() function.

We are not going to study these this semester. However, a


graphic illustrating the interrelationships between them is
depicted next.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

File Processing
Opening a File

To open a file, we do the following:


Create a pointer to a FILE stream (defined in <stdio.h>)
FILE * cfPtr; // cfPtr is a programmer defined
name

Call the fopen() function and assign the return value to that FILE
stream pointer.

That FILE stream can then be used with any of the I/O
functions.

10

File Processing
Opening a File
The fopen() function prototype:
FILE* fopen(const char* filename, const char* mode);

The filename parameter is a string that contains the file name.


(Dont forget to use double-backslashes on Windows systems.)
The mode parameter tells fopen() how to open the file (open for
reading, writing, or append, binary or not).
If the file can be opened as specified, a pointer to a FILE stream is
returned that can be used with other functions.
If the file could not be opened, NULL is returned.

An example use of fopen() might be:


FILE * cfPtr = fopen (data.txt, r);
11

File Processing
Opening a File
The fopen() function prototype:
FILE* fopen(const char* filename, const char* mode);

A more common way to open a file would include a test of the return
value from fopen() to see if it is NULL. If it is, then there has been
an error opening the file:
#include <stdio.h>
FILE * cfPtr;
if ( (cfPtr = fopen (filename.txt, w)) == NULL )
printf (There has been a file error.);
else
{
// proceed with normal processing
}

12

Example of Sequential-Access File

C imposes no structure on a file.


Thus, notions such as a record of a file do not
exist as part of the C language.
The following example shows how you can
impose your own record structure on a file.
Figure 11.2 creates a simple sequential-access
file that might be used in an accounts
receivable system to help keep track of the
amounts owed by a companys credit clients.
2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Example of Sequential-Access File (Cont.)

For each client, the program obtains an account


number, the clients name and the clients balance
(i.e., the amount the client owes the company for
goods and services received in the past).
The data obtained for each client constitutes a
record for that client.
The account number is used as the record key in
this applicationthe file will be created and
maintained in account-number order.
2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Example of Sequential-Access File

The program assumes the user enters the records


in account-number order.
In a comprehensive accounts receivable system, a
sorting capability would be provided so the user
could enter the records in any order.
The records would then be sorted and written to
the file.
[Note: Figures 11.611.7 use the data file created
in Fig. 11.2, so you must run Fig. 11.2 before
Figs. 11.611.7.]
2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.

2016 Pearson Education, Inc.,


Hoboken, NJ. All rights reserved.

2016 Pearson Education, Inc.,


Hoboken, NJ. All rights reserved.

Now lets examine this program.


cfPtr is a pointer to a FILE structure.
A C program administers each file with a separate FILE structure.
You need not know the specifics of the FILE structure to use files,
but you can study the declaration in stdio.h if you like.
We saw how the FILE structure leads indirectly to the operating
systems file control block (FCB) for a file.

Each open file must have a separately declared pointer of


type FILE thats used to refer to the file.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

The file name "clients.dat" is used by the


program and establishes a line of communication
with the file.
The file pointer cfPtr is assigned a pointer to the
FILE structure for the file opened with fopen.
Function fopen takes two arguments: a filename
(which can include path information leading to the
files location) and a file open mode.
The file open mode "w" indicates that the file is to be
opened for writing.
If a file does not exist and its opened for writing,
fopen creates the file.
1992-2013 by Pearson Education, Inc.
All Rights Reserved.

If an existing file is opened for writing, the contents of


the file are discarded without warning.
In the program, the if statement is used to determine
whether the file pointer cfPtr is NULL (i.e., the file
open attempt is unsuccessful).
If its NULL, the program prints an error message and
terminates.
Otherwise, the program processes the input and writes
it to the file.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

File Processing
Using a File Opening mode

A file may be opened in any one of 12 modes.


The mode is indicated by the second input parameter of
the fopen() function:
FILE* fopen(const char* filename, const
char* mode);
The following letters have meaning for the mode:
r

Opens an existing file for reading. Error if the file does


not exist (NULL returned). File marker at beginning.

Opens a file for writing. File is created if it doesnt exist;


existing data discarded if it does. File marker at
beginning.

Opens a file for appending. File is created if it doesnt


exist; all writing is done at the end of the file.

21

File Processing
Using a File Opening mode

The mode is indicated by the second input parameter of the


fopen() function:

FILE* fopen(const char* filename, const


char* mode);

A plus sign may be added to the letter (+) in the opening mode
argument. This indicates that the file may be updated, no matter
what its opening mode was:
r+
w+
a+

Opens an existing file for update (reading and writing). Error if


file doesnt exist. File position marker at beginning.
Opens a file for update (reading and writing). File is
created if it doesnt exist. If the file exists, existing data
discarded. File position marker at beginning.
Opens a file for update (reading and writing). File is
created if it doesnt exist. All writing is done at the end of
the file.
22

File Processing
Using a File Opening mode

The mode is indicated by the second input parameter of


the fopen() function:
FILE* fopen(const char* filename, const
char* mode);

Lastly, it is possible to open a file for binary reading and


writing. This is done by adding a b to the mode string.
rb+
wb+
ab+

opens an existing binary file for update(reading and


writing; error if file doesnt exist).
opens a binary file for writing (reading and writing; file is
created if it doesnt exist; existing data discarded).
opens a binary file for update (reading and writing; file is
created if it doesnt exist; all writing is done at the end of
the file).
23

2016 Pearson Education, Inc.,


Hoboken, NJ. All rights reserved.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

UT D

Using a File
Book 11.3.4, 11.4

Writing into a File

Function fprintf is equivalent to printf except that


fprintf also receives as an argument a file pointer for
the file to which the data will be written.

int fprintf(FILE *stream, const char


*format, ...)

If successful, the total number of characters printed is


returned. Otherwise, returns a negative number.

This function works just like printf() does with the


console. In fact, fprintf (stdout, ..., ...)
works similarly to printf (..., ...).
29

2016 Pearson Education, Inc.,


Hoboken, NJ. All rights reserved.

Reading from a File

To read formatted data from a file, we can use the file


equivalent to scanf():
int fscanf(FILE * stream, const char*
format, ...);

This function works just like scanf() does with the


console. In fact, fscanf (stdin, ..., ...)
works similarly to scanf (..., ...).

The number of data elements successfully read is returned.


A negative number is returned if nothing is read.

31

Reading from a File

When reading from an input file, it is very important to


not read past the end of the file.
Attempting to do so will lead to a bad error.

In C, we can use the feof() function to prevent this.


feof() returns true if data is EOF:
while ( !feof(cfPtr) )
{
/* Get next item from file using fscanf and
process */
}

feof(stdin) can be used to detect if the user types

EOF at the standard input (keyboard)


32

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

The program prompts the user to enter the fields for each
record or to enter end-of-file (EOF) when data entry is
complete.
Figure 11.3 lists the key combinations for entering end-offile for various computer systems.
Function feof to determine whether the end-of-file
indicator is set for the file to which stdin refers.
The end-of-file indicator informs the program that theres no more
data to be processed.

In Fig. 11.2, the end-of-file indicator is set for the standard


input when the user enters the end-of-file key combination.
The argument to function feof is a pointer to the file being
tested for the end-of-file indicator (stdin in this case).
1992-2013 by Pearson Education, Inc.
All Rights Reserved.

The function feof returns a nonzero (true) value


when the end-of-file indicator has been set; otherwise,
the function returns zero.
The while statement that includes the feof call in
this program continues executing as long as the end-offile indicator is not set.
The data may be retrieved later by a program designed
to read the file (see Section 11.4).

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

File Processing
Using a File
Remember that scanf() and fscanf() will tokenize
around white spaces.
It is frequently useful to be able to read (write) whole lines
from (to) a file. The following two functions work for that
purpose:
fgets()
fputs()

36

File Processing
Using a File
fgets()
char * fgets (char * strPtr, int size, FILE
*cfPtr);

The function fgets() reads up to size-1 characters from the


given file stream and puts them into strPtr. It appends a NULL
(\0) to the end.
The size parameter can be used to prevent an overrun on the
input buffer.
fgets() will stop when it reaches the end of a line (\n) on the
input, in which case strPtr will be terminated with a newline. If
fgets() reaches size-1 characters or encounters the EOF
before the end of line is encountered, strPtr will be nullterminated only.
fgets() returns strPtr on success, and NULL on an error.
37

File Processing
Using a File

fputs()
int fputs (const char * strPtr, FILE * cfPtr);

The function fputs() will write the string strPtr to the file
fp.

The \0 character is dropped. No newline is appended (it is up to


the programmer to terminate the line with a newline if needed).
If the write is successful, fputs() returns a non-negative integer.
If not, it returns EOF.

38

File Processing
Files and Streams

To write a character into a file

int fputc(int char, FILE *cfPtr);

If there are no errors, the same character that has been


written is returned. If an error occurs, EOF is returned and
the error indicator is set.
Example
The function call fputc( 'a', stdout ) writes the
character 'a' to stdoutthe standard output.

Several other functions used to read data from standard


input and write data to standard output have similarly
named file processing functions.

39

File Processing
Files and Streams

To read a character into a file


int fgetc(FILE *cfPtr);
This function returns the character read as an unsigned char
cast to an int or EOF on end of file or error.
fgetc(stdin)reads one character from stdin
(standard input)

40

File Processing
Input/Output
File stream

Standard stream

Formatted read

int fscanf(FILE *
cfPtr, const char*
format, ...)

int scanf(const
char *format,
...)

Formatted write

int fprintf(FILE
*cfPtr, const char
*format, ...)

int printf(const
char *format,
...)

Read a line

char *fgets (char *


strPtr, int size,
FILE *cfPtr)

char *gets(char
*strPtr)

Write a line

int fputs (const


char * strPtr, FILE
* cfPtr)

int puts(const
char *strPtr)

Read a char

int fgetc(FILE
*cfPtr)

int getchar(void)

Write a char

int fputc(int char,


FILE *cfPtr)

int putchar(int
char)

41

Resetting the File Position Pointer


To retrieve data sequentially from a file, a program
normally starts reading from the beginning of the file
and reads all data consecutively until the desired data is
found.
It may be desirable to process the data sequentially in a
file several times (from the beginning of the file)
during the execution of a program.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

The statement
rewind( cfPtr );

causes a programs file position pointerwhich indicates


the number of the next byte in the file to be read or
writtento be repositioned to the beginning of the file (i.e.,
byte 0) pointed to by cfPtr.
The file position pointer is not really a pointer.
Rather its an integer value that specifies the byte in the file at which
the next read or write is to occur.

This is sometimes referred to as the file offset.


If the file was opened for append, however, all writes will
still go to the end of the file.
1992-2013 by Pearson Education, Inc.
All Rights Reserved.

File Processing
Using a File
The file position index can be changed, even with text files, by
using the following function:

int fseek (FILE * cfPtr, int offset, int


origin);
The origin value can take one of three pre-defined constants:
SEEK_SET indicates the beginning of the file.
SEEK_CUR indicates the current position of the file.
SEEK_END indicates the end of the file.

The offset value is calculated as an offset from the origin,


in number of bytes. Negative numbers are possible.
fseek() returns 0 if successful; non-zero on error.
44

UT D

Closing a File
Book 11.3.5

After the user enters end-of-file, the program closes the


clients.dat file with fclose and terminates.
Function fclose also receives the file pointer (rather
than the filename) as an argument: fclose(cfPtr);
If function fclose is not called explicitly, the
operating system normally will close the file when
program execution terminates.
This is an example of operating system
housekeeping.

1992-2013 by Pearson Education, Inc.


All Rights Reserved.

2016 Pearson Education, Inc.,


Hoboken, NJ. All rights reserved.

Das könnte Ihnen auch gefallen