C Programming Language Tutorial

Variables and Data Types

Input/Output

Looping and Selection Structures

Array

Functions

Preprocessing Command

Pointer

Structure

File Operations

Important Knowledge

Read And Write Files as Characters (fgetc() And fputc() Function) in C Programming Language

In this tutorial, we'll explore the fgetc() and fputc() functions in the C programming language, which are used to read and write single characters to and from a file. We'll cover the basic syntax, usage, and provide some examples to demonstrate their functions.

Basic Syntax

Before using fgetc() and fputc(), you should include the stdio.h header at the beginning of your C program.

#include <stdio.h>

The basic syntax for fgetc() and fputc() is as follows:

int fgetc(FILE *stream);
int fputc(int c, FILE *stream);
  • fgetc(): This function reads a single character from the given stream and returns its value as an integer. If an error occurs or the end of the file is reached, it returns EOF (end-of-file).
  • fputc(): This function writes a single character (specified by the integer c) to the given stream. If the operation is successful, it returns the written character as an integer. Otherwise, it returns EOF.

Opening and Closing Files

Before using fgetc() and fputc(), you need to open the file with fopen() and close it with fclose() when you're done.

The syntax for fopen() and fclose() is:

FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
  • filename: The name of the file to be opened.
  • mode: The mode in which the file is opened, such as "r" for reading, "w" for writing, and "a" for appending.
  • stream: The file pointer to the open file.

Basic Usage

Let's start with a simple example of reading a single character from a file:

#include <stdio.h>

int main() {
    FILE *file = fopen("input.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int c = fgetc(file);
    if (c != EOF) {
        printf("Read character: %c\n", c);
    }

    fclose(file);
    return 0;
}

In this example, we open the file input.txt for reading, read the first character using fgetc(), and then close the file.

Next, let's write a single character to a file:

#include <stdio.h>

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

    int c = 'A';
    if (fputc(c, file) != EOF) {
        printf("Wrote character: %c\n", c);
    }

    fclose(file);
    return 0;
}

In this example, we open the file output.txt for writing, write the character 'A' using fputc(), and then close the file.

  1. Reading characters from a file with fgetc() in C:

    • Description: fgetc() is used to read characters from a file. It returns the character read or EOF (End of File) on reaching the end of the file.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("input.txt", "r");
          if (file != NULL) {
              int character;
      
              // Read characters until end of file
              while ((character = fgetc(file)) != EOF) {
                  printf("%c", character);
              }
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  2. Writing characters to a file using fputc() in C language:

    • Description: fputc() is used to write a character to a file. It returns the character written or EOF on error.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("output.txt", "w");
          if (file != NULL) {
              char character = 'A';
      
              // Write a character to the file
              fputc(character, file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  3. Sequential file processing with fgetc() and fputc() in C:

    • Description: Combine fgetc() and fputc() for sequential processing, e.g., copying one file to another.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *source = fopen("source.txt", "r");
          FILE *destination = fopen("destination.txt", "w");
      
          if (source != NULL && destination != NULL) {
              int character;
      
              // Read characters from source and write to destination
              while ((character = fgetc(source)) != EOF) {
                  fputc(character, destination);
              }
      
              fclose(source);
              fclose(destination);
          } else {
              printf("Error opening files.\n");
          }
      
          return 0;
      }
      
  4. Character-by-character file I/O in C programming:

    • Description: Process files character by character using fgetc() and fputc() for fine-grained control.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("example.txt", "r+");
          if (file != NULL) {
              int character;
      
              // Read characters and perform some processing
              while ((character = fgetc(file)) != EOF) {
                  // Modify the character (e.g., convert to uppercase)
                  character = toupper(character);
                  // Write the modified character back to the file
                  fputc(character, file);
              }
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  5. Handling end-of-file and error conditions with fgetc() in C:

    • Description: Check for EOF to handle the end of the file and use feof() to check for file-related errors.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("example.txt", "r");
          if (file != NULL) {
              int character;
      
              // Read characters until end of file or error
              while ((character = fgetc(file)) != EOF && !feof(file)) {
                  // Process the character
                  printf("%c", character);
              }
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  6. C code examples demonstrating fgetc() and fputc() usage:

    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *source = fopen("source.txt", "r");
          FILE *destination = fopen("destination.txt", "w");
      
          if (source != NULL && destination != NULL) {
              int character;
      
              // Read characters from source and write to destination
              while ((character = fgetc(source)) != EOF) {
                  fputc(character, destination);
              }
      
              fclose(source);
              fclose(destination);
          } else {
              printf("Error opening files.\n");
          }
      
          return 0;
      }
      
  7. Efficient buffering techniques for file I/O in C:

    • Description: Use buffering to enhance performance. For example, use setbuf() or setvbuf() to set a custom buffer.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("buffered.txt", "w");
          if (file != NULL) {
              char buffer[BUFSIZ];
      
              // Set a custom buffer for the file
              setbuf(file, buffer);
      
              // Write to the file with the custom buffer
              fputs("Hello, Buffered IO!", file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  8. Random access file operations with fgetc() and fputc() in C:

    • Description: Use fseek() to set the file position and then use fgetc() or fputc() for random access.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("random_access.txt", "r+");
          if (file != NULL) {
              // Set file position to the 5th character
              fseek(file, 4, SEEK_SET);
      
              // Read and print the character at the 5th position
              int character = fgetc(file);
              printf("Character at position 5: %c\n", character);
      
              // Set file position to the end
              fseek(file, 0, SEEK_END);
      
              // Write a character at the end of the file
              fputc('X', file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }