English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

fgetc() and fputc() in C

fgetc()

This featurefgetc()used to read characters from a file. It returns the character pointed to by the file pointer, or EOF if successful.

This isfgetc()C language syntax,

int fgetc(FILE *stream)

This isfgetc()C language example,

Assuming we have the following content in the "new.txt" file-

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

Now, let's look at an 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();
}

This is the output,

Output Result

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

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

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

fputc()

This functionfputc()used to write characters to a file. It writes the character to the file and returns EOF if successful.

This isfputc()C language syntax,

int fputc(int character, FILE *stream)

Here,

char-The character will be written to the file.

Stream-This is a pointer to the file where the character to be written is located.

This isfputc()C language example,

Assuming we have the following content in the "new.txt" file-

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

Now, let's look at an example-

Example

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

This program will modify the "new.txt" file. It will not display any output on the screen but will directly modify the file. 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",fputc()and used to write characters to a file.

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