Professional Documents
Culture Documents
Lecture 17c
20/3/01
m
ntroduction
{ Files are places where data can be stored
permanently.
{ Some programs expect the same set of data to
be fed as input every time it is run.
{ Cumbersome.
{ Better if the data are kept in a file, and the
program reads from the file.
{ Programs generating large volumes of output.
{ Difficult to view on the screen.
{ Better to store them in a file for later viewing/
processing
m
m
aasic File Operations
{ pening a file
{ Reading data from a file
{ Writing data to a file
{ Closing a file
m
Opening a File
{ ë file must be Ơopenedơ before it can be used.
FILE *fp;
:
fp = fopen (filename, mode);
{ fp is declared as a pointer to the data type FILE.
{ filename is a string - specifies the name of the file.
{ fopen returns a pointer to the file which is used in all
subsequent file operations.
{ mode is a string which specifies the purpose of
opening the file:
Ơrơ :: open the file for reading only
Ơwơ :: open the file for writing only
Ơaơ :: open the file for appending data to it
m
Contd.
{ Points to note:
{ Several files may be opened at the same
time.
{ For the Ơwơ and Ơaơ modes, if the named file
does not exist, it is automatically created.
{ For the Ơwơ mode, if the named file exists, its
contents will be overwritten.
m
amples
FILE *empl ;
char filename[25];
scanf (Ơ%sơ, filename);
empl = fopen (filename, Ơrơ) ;
m
Closing a File
×
!
!
"
m
Contd.
m
ample
á á á
*+
m
m
Arguments to main ()
{ Command line arguments are parameters supplied to
a program, when the program is invoked.
cc myfile.c
cc xyz.c -lm
netscape www.mailcity.com
average 10 20 30 40 50
{ 2ow do these parameters get into the program?
{ Every C program has a main function.
{ main can take two arguments conventionally called argc and
argv.
{ Information regarding command line arguments are passed
to the program through argc and argv.
m
choing the command line
arguments
m