fgetc() and fputc() in C


fgetc()

The function fgetc() is used to read the character from the file. It returns the character pointed by file pointer, if successful otherwise, returns EOF.

Here is the syntax of fgetc() in C language,

int fgetc(FILE *stream)

Here is an example of fgetc() in C language,

Let’s say we have “new.txt” file with the following content −

0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo

Now, let us see the example −

Example

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

Here is the output,

Output

0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo

In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file.

FILE *f;
char s;
clrscr();
f=fopen("new.txt","r");

fputc()

The function fputc() is used to write the character to the file. It writes the character to the file, if successful otherwise, returns EOF.

Here is the syntax of fputc() in C language,

int fputc(int character, FILE *stream)

Here,

char − The character is to be written to the file.

stream − This is the pointer to the file where character is to be written.

Here is an example of fputc() in C language,

Let’s say we have “new.txt” file with the following content −

0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo

Now, let us see the example −

Example

#include <stdio.h>
void main() {
   FILE *f;
   f = fopen("new.txt", "w");
   fputc('a',f);
   fclose(f);
}

The program will modify the “new.txt” file. It will not display any output to the screen but it will modify the file directly. You can check the modified file. The following text is the modified text of the file −

A

In the above program, the file pointer f is used to open the file “new.txt” and fputc() is used to write the character to the file.

FILE *f;
f = fopen("new.txt", "w");
fputc('a',f);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements