0
0
CHow-ToBeginner · 3 min read

How to Use getc and putc in C: Simple Guide with Examples

In C, getc reads a single character from a file stream, and putc writes a single character to a file stream. Both functions work with FILE* pointers and are useful for character-by-character file input/output.
📐

Syntax

getc reads one character from a file stream and returns it as an int. It returns EOF if the end of file or an error occurs.
putc writes one character to a file stream and returns the character written or EOF on error.

  • int getc(FILE *stream);
  • int putc(int char, FILE *stream);
c
int getc(FILE *stream);
int putc(int char, FILE *stream);
💻

Example

This example opens a file named input.txt for reading and output.txt for writing. It reads each character from the input file using getc and writes it to the output file using putc. It demonstrates basic character-by-character file copying.

c
#include <stdio.h>

int main() {
    FILE *infile = fopen("input.txt", "r");
    FILE *outfile = fopen("output.txt", "w");

    if (infile == NULL || outfile == NULL) {
        perror("Error opening file");
        return 1;
    }

    int ch;
    while ((ch = getc(infile)) != EOF) {
        putc(ch, outfile);
    }

    fclose(infile);
    fclose(outfile);
    return 0;
}
⚠️

Common Pitfalls

  • Not checking if the file opened successfully before using getc or putc.
  • Using char type to store the result of getc which can cause errors because getc returns int to handle EOF.
  • Not closing files after finishing reading or writing.
c
#include <stdio.h>

int main() {
    FILE *file = fopen("file.txt", "r");
    if (!file) {
        perror("Failed to open file");
        return 1;
    }

    // Wrong: storing getc result in char
    // char ch = getc(file); // May cause errors on EOF

    // Right: use int to store getc result
    int ch = getc(file);

    if (ch != EOF) {
        putc(ch, stdout); // write to console
    }

    fclose(file);
    return 0;
}
📊

Quick Reference

getc and putc are simple functions for reading and writing one character at a time from/to files.

  • getc(stream): Reads next character or EOF.
  • putc(char, stream): Writes character or returns EOF on error.
  • Always check for NULL file pointers before use.
  • Use int type to store getc results to detect EOF.
  • Close files with fclose() when done.

Key Takeaways

Use getc to read one character from a file stream and putc to write one character to a file stream.
Always store getc's return value in an int to properly detect EOF.
Check if files open successfully before reading or writing.
Close files with fclose to avoid resource leaks.
getc and putc are useful for simple character-by-character file operations.