Wa0000.
Wa0000.
Introduction
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.
Opening a file
Reading data from a file
Writing data to a file Closing a file
Opening a File
A file must be "opened" before it can be
used.
:
FILE *fp;
Contd.
Points to note:
Examples
FILE *empl;
char filename[25];
scanf("%s", filename);
empl
=
6
CO
Closing a File
fclose (xyz);
Read/Write Operations on
Files
The simplest file input-output (I/O) function
are getc and putc.
getc is used to read a character from a file and
return it.
char ch; FILE *fp;
ch = getc (fp);
getc will return an end-of-file marker EOF, when the
end of the file has been reached.
8
00
main() {
FILE *in, *out;
char c;
in
=
fopen("infile.dat", "r");
out = fopen("outfile.dat", "w");
Contd.
H
We can also use the file versions of scanf
and printf, called fscanf and fprintf.
General format:
10
Some Points
NULL)
printf ("\n Unable to open file");
11
Example
typedef struct {
int
roll;
char dept_code[6];
float cgpa;
} STUD:
main() {
FILE *stud;
STUD s;
while (1) {
}
if (feof (stud)) break;
fscanf (stud, "%d %s %f", &s.roll,
count ++;
s.dept code, &s.cgpa);
sum += s.cgpa;
12
Arguments to main ()
Command line arguments are parameters
supplied to a program, when the program is
invoked.
cc myfile.c
Cc xyz.c -Im
netscape www.mailcity.com
average 10 20 30 40 50
13
14