/    /  File Handling Functions

File Handling Functions

 

Reading Character from a file: fgetc( ) or getc( )

 

fgetc( ) or getc( ) is a predefined file handling function which is used to read a single character from a existing file opened in read(“r”) mode by fopen( ), which is same as like getchar( ) function.

 

Syntax:

 

 ch_var= fgetc(filepointer); (Or) ch_var=getc(filepointer);

 

Example:

 

char ch;
ch=fgetc(fp); (Or) ch=getc(fp);
where ‘ch’ is a character variable to be written to the file.
where ‘fp’ is a file pointer object.

 

  • getc( ) or fgetc( ) gets the next character from the input file to which the file pointer fppoints to. The function getc( ) will return an end-of-file(EOF) marker when the end of the file has been reached or it if encounters an error.
  • On Success the function fputc( ) or putc( ) will return the value that it has written to the file, otherwise it returns EOF.

 

Example Program:

 

A program to read a file.

 

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

fp=fopen("DATA1.txt","r"); /* DATA1.txt is an already existing file with content */
printf("Text from file is:\n");
while((ch=fgetc(fp))!=EOF)/* (Or) while((ch=getc(fp))!=EOF)*/
printf("%c",ch);
fclose(fp);
}

 

Output:

 

File Handling Functions

 

Writing Or Printing Character in a file: fputc( ) or putc( )

 

  • fputc( ) or putc( ) is a predefined file handling function which is used to print a single character in a new file opened in write(“w”) mode by fopen( ), which is same as like putchar( ) function.

 

Syntax:

 

 fputc(ch_var , filepointer); (Or) putc(ch_var , filepointer);

 

Example:

 

fputc(ch, fp); (Or) putc(ch, fp);
Where ‘ch’ is a character variable.
Where ‘fp’ is a file pointer object.

 

Example Program:

 

To write a Character in a file and read a Character from a file.

 

#include<stdio.h>
main( ){
FILE *fp;
char ch;
fp=fopen("DATA1.txt","w");
printf("Enter the Text:\n");
printf("Use Ctrl+z to stop entry \n");
while((ch=getchar( ) )!=EOF) /* fputc(ch,fp); /* (Or) putc(ch,fp); */
fclose(fp);
printf("\n");
fp=fopen("DATA1.txt","r");
printf("Entered Text is:\n");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}

 

Output:

 

File Handling Functions