C fputc() and fgetc()

The fputc() function is used to write characters to the file.

Syntax of fputc() function




              
fputc(char ch, FILE *fp);



The fputc() function takes two arguments, first is the character to be written to the file and second is the file pointer where the character will be written.

Example of fputc() function




       #include<stdio.h>

       void main()
       {
              FILE *fp;
              char ch;

              fp = fopen("file.txt","w");            //Statement   1

              if(fp == NULL)
              {
                     printf("\nCan't open file or file doesn't exist.");
                     exit(0);
              }

              while((ch=getchar())!=EOF)           //Statement   2
                  fputc(ch,fp);

              printf("\nData written successfully...");

              fclose(fp);
       }



Output :

Hello friends, my name is kumar.^Z

Data written successfully...

In the above example, statement 1 will create a file named file1.txt in write mode. Statement 2 is a loop, which take characters from user and write the character to the file, until user press the ctrl+z to exit from the loop.

Example:




#include <stdio.h>
main()
{  
   FILE *fp;  
   fp = fopen("file1.txt", "w");//opening file  
   fputc('a',fp);//writing single character into file  
   fclose(fp);//closing file  
}  




file1.txt

a

The fgetc() function

The fgetc() function is used to read characters form the file.

Syntax of fgetc() function




              char fgetc(FILE *fp);



The fgetc() function takes the file pointer indicates the file to read from and returns the character read from the file or returns the end-of-file character if it has reached the end of file.

Example of fgetc() function




       #include<stdio.h>

       void main()
       {
              FILE *fp;
              char ch;

              fp = fopen("file.txt","r");            //Statement   1

              if(fp == NULL)
              {
                     printf("\nCan't open file or file doesn't exist.");
                     exit(0);
              }

              printf("\nData in file...\n");

              while((ch = fgetc(fp))!=EOF)           //Statement   2
                  printf("%c",ch);

              fclose(fp);
       }



Output :

Data in file...

Hello friends, my name is kumar.

In the above example, Statement 1 will open an existing file file1.txt in read mode and statement 2 will read all the characters one by one upto EOF(end-of-file) reached.

Example:


#include<stdio.h>
#include<conio.h>
void main(){  
FILE *fp;  
char c;  
clrscr();  
fp=fopen("myfile.txt","r");  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
fclose(fp);  
getch();  
}  



myfile.txt

this is simple text message




Instagram