Files - 2 File I/O functions

File I/O functions :

C provides various functions to handle file I/O operations. Now we will see the functions of file,

getc() : It is used to read a single character at a time from file.

Syntax :

character-variable = getc( file-pointer );

Example:

c =  getc (fp);

putc() : It is used to write a single character into the file.

Syntax :

putc( character, file-pointer );

Example:

putc (c, fp);

Example for putc () function

/* Program to Demonstrate the putc () function */

#include < stdio.h >
main()
{
FILE *fp;
char c;

fp=fopen("Sample.txt","w");

do
{
c=getchar();
putc(c,fp);
}while(c!=EOF);
fclose(fp);
}




    In the above program initially a file pointer fp and a character variable c is declared. Using fopen () function a file sample.txt is opened in write mode. In the do-while loop,

c = getchar(); 

accepts a character typed by the user and assigns it to character variable c. Using putc() function, character present in variable c will be written into the file pointed by fp. This process will repeat until a user type ctrl+z to indicate the end of file. Later file will be closed using fclose() function.

Example for Demonstrating getc() function:

/* Program to read characters from the file */
#include < stdio.h >
main()
{
FILE *fp;
char c;

fp=fopen("Sample.txt","r");

while(!feof(fp))
{
c=getc(fp);
printf("%c",c); /*putchar(c);*/
}
fclose(fp);
}

     In the above program initially a file pointer fp and a character variable c is declared. Using fopen () function a file sample.txt is opened in read mode. In the while loop, a function feof() is used. If the file pointer fp is reached end of the file then it returns 1 otherwise 0. Loop will stop when fp reaches end of file otherwise it continue with iterations of while loop. Inside the loop a statement,

c = getc( fp );

reads a character from the file pointed by fp and assigns it to variable c then using printf() or putchar ()  it can be printed on the monitor.






Comments