Download as ppsx, pdf, or txt
Download as ppsx, pdf, or txt
You are on page 1of 18

CS 112

PROGRAMMING LANGUAGE 1
Spring 2015

1 By Wessam El-Behaidy and Marwa M. A. Elfattah


Assistant professors in
Department of Computer Science
C File
Processing
CS112_lect 10_by Wessam El-Behdaidy
INTRODUCTION
 Storage of data in variables and arrays is
temporary—such data is lost when a program
terminates.
 Files are used for permanent retention of data.

 Computers store files on secondary storage


devices, especially disk storage devices.
 The C programming language provides many

Section 11.1
standard library functions for file input and
output. These functions are found in the C
standard library header stdio.h.
3
CS112_lect 10_by Wessam El-Behdaidy
FILES AND STREAMS

 C views each file simply as a sequential stream


of bytes.
 In computer science, a stream is a sequence of
data elements made available over time.
 Normal functions cannot operate on streams as a
whole, as they have potentially unlimited data
 In C, the stream is a common, logical interface to
the various devices of the computer. All input

Section 9.2 & 11.3


and output is performed with streams, which
are sequences of bytes.

4
CS112_lect 10_by Wessam El-Behdaidy
FILES AND STREAMS

 Three streams are automatically opened when


program execution begins—the standard input,
the standard output and the standard error.
 The standard input stream enables a program to

Section 9.2 & 11.3


read data from the keyboard, and the standard
output stream enables a program to print data on
the screen.
5
CS112_lect 10_by Wessam El-Behdaidy
FILES AND STREAMS
 A stream is linked to a file using an open
operation, and is disassociated from a file using a
close operation.
 Each file stream ends with an end-of-file
marker
 Opening a file stream returns a pointer to a FILE
structure that contains information used to

Section 11.3
process the file.

6
CS112_lect 10_by Wessam El-Behdaidy
TEXT FILES AND BINARY FILES
 Each file is just a series of bytes. In general every file
is a binary file, but if the data in it contains only
text, then we could consider it a text file.
 Ex: A C program written in the editor is a text file,
but its compiled version is binary.
 A text file is a stream of characters that a computer
can process sequentially and in forward direction.
They can only read or write data one character at a
time. Some special character conversion may occur in

Section 11.1
input/output operations in text mode
 A binary file is a collection of bytes. No special
processing occurs during the transferring of data
between the disk and the memory. 7
CS112_lect 10_by Wessam El-Behdaidy
OPENING A FILE

 For C File I/O you Modes


need for texta files
to use FILE pointer
r -Open an existing file for reading.
FILE *fp;
w - Create a file for writing. If it exists, discard its contents.
a- To open open
Append; a fileoryou need
create to use
a file the fopen
for writing function
at the file end.
r+ - Open an existing
FILE file for update
*fopen(char (readingchar
*filename, and writing).
*mode );
w+ - Create a file for update. If it exists, discard its contents.
a+ - Open or create a file for update; writing is at the file end.

 Ex: FILE *fPtr; Modes for binary files


rb -Open an existing file for reading.
fPtr = fopen( “client.dat", "w" )

Section 11.4
wb - Create a file for writing. If it exists, discard its contents.
ab - Append; open or create a file for writing at the file end.
rb+success:
On - Open an existing
fPtr file for
is assigned update to
a pointer (reading andstructure
the FILE writing).
wb+
On - Create
failure: a file
fPtr willfor
hasupdate.
NULLIf it exists, discard its contents.
ab+ - Open or create a file for update; writing is at the file end. 8
CS112_lect 10_by Wessam El-Behdaidy
A SEQUENTIAL ACCESS FILE - TEXT FILES
 You use fprintf and fscanf, both of which are similar
to their friends printf and scanf except that you must
pass the FILE pointer as first argument.
 EX: fscanf( fPtr, "%d%s", &account, name);
 fscanf and fprintf can deal with the standard
input/output by using stdin or stdout as the file
pointer, as in:
fprintf( stdout, "%s \n", “test”);
 When you have done working with a file, you should

Section 11.5
close it using the function
int fclose(FILE *a_file);
fclose returns zero if the file is closed successfully.
9
Closing a file can free resources for which other users
or programs may be waiting.
CS112_lect 10_by Wessam El-Behdaidy
EXAMPLE:
When the program reaches the end of
int account; If you use a string literal, use double
the file, Function feof returns true.
backslashes rather than a single
char name[ 30 ]; after the program Open
attemptsfiletoquoted
read the
backslash! It's justReading
File
the way
double balance; nonexistent data for
following
strings are handled from
Pointer
reading
in Cfilethe C++.
and last
FILE *fPtr; line.
if ( ( fPtr = fopen( “c:\\clients.dat", "r“ ) ) == NULL )
printf( "File could not be opened\n" ); Means the file
else { can’t be opened
printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" );
fscanf( fPtr, "%d%s%f", &account, name, &balance );

Section 11.5
while (!feof( fPtr ) ) {
printf( "%-10d%-13s%7.2f\n", account, name, balance );
fscanf( fPtr, "%d%s%f", &account, name, &balance );
} /* end while */ 10

fclose( fPtr );
CS112_lect 10_by Wessam El-Behdaidy
RESETTING THE FILE POSITION POINTER
 A program normally starts reading from the
beginning of the file and reads all data consecutively.
 File position pointer is an integer that indicates
the index of the next byte in the file to be read or
written. This is sometimes referred to as the file
offset.
 The file position pointer is a member of the FILE
structure associated with each file.
 A statement rewind( fPtr ) causes a program’s file

Section 11.5
position pointer to be repositioned to the beginning of
the file (i.e., byte 0)

 Example: Fig 11.8 11


CS112_lect 10_by Wessam El-Behdaidy
RANDOM-ACCESS FILE - FOR BINARY
FILES

 Random access means we can move to any part of


a file and read or write data from it without
having to read through the entire file.
 Individual records of a random access file are
normally fixed in length and may be accessed
directly (and thus quickly).
 The exact location of a record relative to the
beginning of the file can be calculated

Section 11.6
 Data can be inserted in a random-access file
without destroying other data in the file. Data
stored previously can also be updated or deleted
12
without rewriting the entire file.
CS112_lect 10_by Wessam El-Behdaidy
RANDOM-ACCESS FILE
 Function fread reads a specified number of bytes
from the location in the file specified by the file
position pointer
 Function fwrite writes a specified number of bytes
to a file. The data is written beginning at the
location in the file indicated by the file position
pointer.
 Example:

Section 11.7
fwrite( & data, sizeof( int ), 1, fPtr );
In sequential access it was
fprintf( fPtr, "%d", number ); 13
CS112_lect 10_by Wessam El-Behdaidy
RANDOM-ACCESS FILES
 Function fseek sets the file position pointer to a
specific position in the file, then fwrite writes the
data.
int fseek( FILE *stream, long int offset, int
whence );
 offset: is the number of bytes to seek from location
whence in the file pointed to by stream.

Section 11.8
 The argument whence can have one of three values:
 SEEK_SET: seek starts at the beginning of the file.
 SEEK_CUR: seek starts at the current location.
 SEEK_END: seek starts at the end of the file.
14
CS112_lect 10_by Wessam El-Behdaidy
EXAMPLE
struct Data {
int acctNum; char lastName[ 15 ];
char firstName[ 10 ]; double balance;}
int main(){
struct Data D = { 0, “", "", 0.0 };
FILE * fptr;
if ( (fptr = fopen( "credit.dat", “wb" ) ) == NULL ) {
printf( "File could not be opened.\n" ); }
else {
fwrite(& D, sizeof( struct Data ) , 1 , fptr );
fclose(fptr);
Size of of
Number the recordwhich
records which
}
willbe
will bewritten
written 15
return 0
}; Could be array
CS112_lect 10_by Wessam El-Behdaidy
EXAMPLE

struct Data D;
FILE fPtr;
if ( (fPtr = fopen( "credit.dat", “rb" ) ) == NULL ) {
printf( "File could not be opened.\n" ); }
else {
The byte positions in the
int Num;
file start with 0
scanf( “%d", Num);
fseek( fPtr, ( Num - 1 ) *sizeof( struct Data ),
SEEK_SET );
fread( &D, sizeof( struct Data ) , 1 , fPtr );
printf( "%d %s %s %f\n", D.acctNum,
client.lastName, D.firstName, D.balance ); 16
fclose(fptr);
}
CS112_lect 10_by Wessam El-Behdaidy
FILES INPUT OUTPUT:
 char c = fgetc(fptr); //return one character
 fputc(c, cfptr); //put one character to a file
End of file
 Ex:

while ( (c = fgetc(fptr)) != EOF )


printf("char:'%c'\n",c);
The file: The output:
char:'U'
UW
CE char:'W'
char:’
'
char:'C’
char:'E' 17

char:'
ASSIGNMENT

You might also like