fputc() and fgetc() in C

In C, the functions fputc() and fgetc() are used for handling character-based input and output operations in files. They are part of the C standard library and provide a way to interact with files at the character level.

fputc()

The fputc() function is used to write a single character to a file. It takes two arguments: the character to be written and the file pointer where the character will be written.

Syntax

                        
int fputc(int character, FILE *stream);
                        
                    

The function returns the character written, or EOF if an error occurs.

Example: Using fputc()

                        
#include <stdio.h>
int main() 
{
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    fputc('A', file);
    fputc('B', file);
    fputc('C', file);

    fclose(file);          
    return 0;
}
                        
                    

Output:

The characters 'A', 'B', and 'C' are written to the "example.txt" file.

fgetc()

The fgetc() function is used to read a single character from a file. It takes the file pointer as its argument and returns the character read as an unsigned char cast to an int or EOF on error or end of file.

Syntax

                        
int fgetc(FILE *stream);
                    
                    

The function returns the character read as an unsigned char cast to an int or EOF if the end of the file is reached or an error occurs.

Example: Using fgetc()

                        
#include <stdio.h>>
        
int main()
{
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    int ch;
    while ((ch = fgetc(file)) != EOF) {
        printf("%c", ch);
    }
           
        
    fclose(file);
    return 0;
}
                    
                    

Output:

ABC (The characters are read from the "example.txt" file and displayed on the console).

Difference Between fputc() and fgetc()

Aspect fputc() fgetc()
Function Purpose Writes a character to a file. Reads a character from a file.
Return Value The character written or EOF on error. The character read or EOF on error or end of file.
Usage Used for writing characters to files. Used for reading characters from files.

Key Points