fputc function-write one character to the file stream

You can use the fputc function to write a single character to a file stream.

#include <stdio.h>
int fputc (int c, FILE * fp);

The first argument is the character you want to write. The second argument is the file stream.

Sample to write a file character by character

This is a sample to write a file character by character using the fputc function.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main (void) {
  
  // Open the file in read mode
  const char * in_file = "input.txt";
  FILE * in_fp = fopen (in_file, "r");
  if (in_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", in_file);
    exit (1);
  }

  // Open the file in write mode
  const char * out_file = "output.txt";
  FILE * out_fp = fopen (out_file, "w");
  if (out_fp == NULL) {
    fprintf (stderr, "Can't open file%s\n", out_file);
    exit (1);
  }
  
  // Read and output to file
  int32_t ch;
  while (ch = fgetc (in_fp)) {
    // If EOF is returned
    if (ch == EOF) {
      // Check if it is the end of the file
      if (feof (in_fp)) {
        break;
      }
    }
    fputc (ch, out_fp);
  }
  
  // Close the file with the fclose function
  fclose (in_fp);
  fclose (out_fp);
}

Associated Information