Thursday, 14 February 2013

Reading from and writing to Files in C Language



In C, character input-output functions from files are simple extensions of the corresponding functions for input-ouput from/to the terminal. So, there are funcitons such as:

fgetc()
fputc()

The only additional parameter of both functions is the appropriate file pointer, so that the file to be used for input-output is known.

The following code performs the actual copying of contents of a.dat to b.dat:

#include<stdio.h>
main()
{
char c;
:
:
while((c=fgetc(ptr1))!= EOF)
fputc(c, ptr2);
}

The fgetc() function reads one character at a time from a file, assigns it to a character variable, and moves the file pointer to the next character.

fgetc() actually returns an integer type of value, which is type cast into a character type before being assigned to c.

0 comments:

Post a Comment

Powered by Blogger.