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

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C File fputc() and fgetc()

Writing to a file: fputc() function

The fputc() function is used to write a single character to the file. It outputs the character to the stream.

Syntax:

int fputc(int c, FILE *stream)

#include <stdio.h>  
void main() {  
   FILE *fp;
   fp = fopen("file1.txt//Open the file
   fputc('a', fp);//Write a single character to the file
   fclose(fp);//Close the file
}

file1.txt

a

Reading a file: fgetc() function

The fgetc() function returns a single character from the file. It retrieves a character from the stream. It returns EOF at the end of the file.

Syntax:

int fgetc(FILE *stream)

#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