Friday, March 11, 2011

Reading from and writing on File in C Programming language


Reading Characters from A file

To read a file character by character, we make use of the getc() standard function available to us.
Syntax of getc() :- <character variable> = getc(<file pointer>);

Writing Characters To A File

To write data into a file character by character, we make use of the putc() standard function in C. putc() function is analogous to the putchar() function already studied.
Syntax of funcyion putc() :- putc(< character variable >, < file pointer >);
Another function which can be used to write data into a file character by character is the fputc() function. fputc() and putc() function both work in exactly the same manner.
Syntax of fputc() :- fputc(< character variable >, < file pointer >);

What is End of File

Any function which enables reading of data from the file will return EOF, when the end of the file has been reached. This implies that reading of data from the file should terminate when EOF if encountered.

Besides, the end of file marker, EOF, 'C' also provides the feof() function, which returns the value true (non zero) if the end of file has been reached or returns false (zero).

Syntax of function feof() :-feof(< file pointer >);
The following program will create a file and value (single line) will be inserted into the file

#include< stdio.h >
 void main ()
 {
 FILE *p;
 char ch;
 printf ("\nNew file is created and write now :-\n");
 p=fopen ("dd1.txt","w");
 while ((ch=getchar ())!='\n')
 putc (ch, p);
/* This function will write the character (first argument) on the buffer.*/
 fclose (p);
 }
getchar () function reads a character from the terminal and putc () function writes it on the file. (Single line can be entered here)

If you want to enter multiple lines then the program will be:

#include< stdio.h >
 void main ()
 {
 FILE *p;
 char ch;
 printf ("\nNew file is created and write now (multiple lines) :-\n");
 p=fopen ("dd1.txt","w");
 while ((ch=getchar ())!=EOF)
 putc (ch, p);
 fclose (p);
 }

In this case after editing the text press ‘Ctrl + Z’ to save the file and Ctrl+Z to generate EOF.




No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner