File I/O
File I/O
1
Files
• A file is an external collection of related data
treated as a unit.
4
• These buffering activities are taken care of
by software know as device drivers or
access methods, which are provided by
the supplier of the Operating System you
are using.
5
Files and Streams
• The computer looks at input and output data,
whether from a physical device such as a
keyboard, or from secondary files, as a stream of
characters or bytes.
6
• The term file table implies that several things are
stored. It contains ALL the info needed to
locate your file wherever it is stored outside of
the computer. It also contains info such as the
file name, the location of its file buffer, and the
current state of the file.
7
File System Basics
• The header <stdio.h> contains:
8
The file pointers(stdin, stdout, stderr-
i.e., Tables) are automatically opened
when the program starts.
9
Three File Pointers
• General form:
18
Closing a File
• General form:
20
• Failure to close a stream invites all kinds
of trouble, including :lost data, destroyed
files, and possible intermittent errors in
your program.
21
Writing a Character
To a File
• putc( ) and fputc( )
• General form:
do {
ch = getc(fp);
} while(ch!=EOF); 23
Why have different functions(getc, fgetc,
putc, fputc) that basicly perform the same?
Good question!
24
/* KTOD: A key to disk program. */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{ KTOD TEST
FILE *fp; Reads characters from the
char ch; keyboard and writes them to a
disk file until the user types a
if(argc!=2) { dollar sign.
printf(''You forgot to enter the filename.\n");
exit(1);
} 25