0
0
CHow-ToBeginner · 3 min read

How to Use fputc in C: Syntax, Example, and Tips

In C, fputc writes a single character to a file stream. You use it by passing the character and the file pointer, like fputc('A', filePointer);. It returns the character written or EOF on error.
📐

Syntax

The fputc function writes one character to the specified file stream.

  • int fputc(int character, FILE *stream);
  • character: The character to write (passed as an int).
  • stream: Pointer to the open file where the character will be written.
  • Returns the character written on success, or EOF on failure.
c
int fputc(int character, FILE *stream);
💻

Example

This example opens a file named output.txt for writing, writes the characters 'H', 'i', and '!' using fputc, then closes the file.

c
#include <stdio.h>

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

    fputc('H', file);
    fputc('i', file);
    fputc('!', file);

    fclose(file);
    return 0;
}
⚠️

Common Pitfalls

Common mistakes when using fputc include:

  • Not checking if the file opened successfully before writing.
  • Passing an invalid or closed file pointer.
  • Not closing the file after writing, which can cause data loss.
  • Confusing fputc with putc or putchar which have different uses.
c
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    // Wrong: Not checking if file is NULL
    fputc('A', file); // May crash if file is NULL

    // Correct way:
    if (file != NULL) {
        fputc('A', file);
        fclose(file);
    } else {
        perror("File open error");
    }
    return 0;
}
📊

Quick Reference

  • fputc(char, filePointer): Write one character to file.
  • Returns the character written or EOF on error.
  • Always check if file pointer is valid before writing.
  • Close the file after writing to save changes.

Key Takeaways

Use fputc to write a single character to a file stream in C.
Always check if the file opened successfully before calling fputc.
Remember to close the file with fclose after writing to save data.
fputc returns the character written or EOF if an error occurs.
Passing an invalid file pointer to fputc can cause program crashes.