Files 421
fcloseffp);
printf Cn Contents read
fp*fopen("data.txt""r");
while Ofeoftfp))
printf <u%t",getc(fp));
J
rMrrpi nr*
K w AAmW At
Write data fe to stop press V: ABCDEFGHIJK.
Contents rtstd: ABCDEFGHIJK.
Explanation In the above program the file named "d a t a . t x t " is opened in written mode. The
characters are read from the keyboard and stored in variable 1 c '. Using f putc () the characters
are written to a file until ' . 9 (Dot) is pressed.
The same file is closed and then it is re-opened in read mode. On reopening of the file character
pointer sets to the beginning of the file. The contents of the file will be displayed on the screen using
g etc ().
3. a ( append) This mode opens a pre-existing file for appending data. If the file doesn't exist then
new file is opened i.e. if the file does not exist then the mode of "a " is same as V
Syntax
fp=fopen ("data.txt"/'a");
Here, if data , tx t file already exists, it will be opened. Otherwise a new file will be opened with
the same name.
13.2 Write a program to open a pre-existing file and add information at the end of file.
Display the contents of the file before and after appending.
# include <0tdio.h >
# include <conio*h>
# include <proces«.h>
void m ain()
{
fXLK *fp j
ehar c j
cXracrO;
printf ("Contents of file before appending Am");
fp*fopen(Mda ta. txt", V ') ;