fputc() fgetc() in C Language

Understanding of fputc() fgetc() in C Language

Hello, fellow C programmers! In this blog post, I’m going to explain two very useful functions for working

with files in C: fputc() and fgetc(). These functions allow you to write and read single characters to and from a file, respectively. They are very simple to use, but also very powerful. Let’s see how they work!

What is a fputc() fgetc() in C Language?

fputc() and fgetc() are two functions in the C programming language that are used for performing unformatted, character-based input and output operations on files. These functions are part of the Standard I/O Library and work with files represented by FILE pointers.

  1. fputc(): fputc() is used for writing a single character to a file. It allows you to write a character to the specified file, which can be useful for creating or modifying text files. The syntax of fputc() is as follows:
   int fputc(int character, FILE *stream);
  • character: The integer value of the character to be written to the file. It is typically of type int, but it represents a character in the file.
  • stream: A pointer to the FILE structure representing the file where you want to write the character. Here’s a simple example of using fputc() to write characters to a file:
   #include <stdio.h>

   int main() {
       FILE *filePtr;
       char ch;

       // Open a file for writing
       filePtr = fopen("output.txt", "w");

       if (filePtr == NULL) {
           perror("Error opening file");
           return 1;
       }

       // Write characters to the file
       for (ch = 'A'; ch <= 'Z'; ch++) {
           fputc(ch, filePtr);
       }

       // Close the file
       fclose(filePtr);

       return 0;
   }

In this example, the program opens “output.txt” in write mode and writes the uppercase alphabet characters to the file.

  1. fgetc(): fgetc() is used for reading a single character from a file. It allows you to read characters one at a time from the specified file. The syntax of fgetc() is as follows:
   int fgetc(FILE *stream);
  • stream: A pointer to the FILE structure representing the file from which you want to read the character. Here’s a simple example of using fgetc() to read characters from a file:
   #include <stdio.h>

   int main() {
       FILE *filePtr;
       int ch;

       // Open a file for reading
       filePtr = fopen("input.txt", "r");

       if (filePtr == NULL) {
           perror("Error opening file");
           return 1;
       }

       // Read characters from the file and print them
       while ((ch = fgetc(filePtr)) != EOF) {
           putchar(ch);
       }

       // Close the file
       fclose(filePtr);

       return 0;
   }

Examples of fputc() fgetc() in C Language?

Certainly! Here are examples of using fputc() for writing characters to a file and fgetc() for reading characters from a file in the C language:

  1. Using fputc() to Write Characters to a File: In this example, we’ll write a series of characters to a file named “output.txt” using fputc().
   #include <stdio.h>

   int main() {
       FILE *filePtr;
       char ch;

       // Open a file for writing
       filePtr = fopen("output.txt", "w");

       if (filePtr == NULL) {
           perror("Error opening file");
           return 1;
       }

       // Write characters from 'A' to 'Z' to the file
       for (ch = 'A'; ch <= 'Z'; ch++) {
           fputc(ch, filePtr);
       }

       // Close the file
       fclose(filePtr);

       printf("Characters written to the file.\n");

       return 0;
   }

This program opens “output.txt” in write mode and writes the uppercase alphabet characters from ‘A’ to ‘Z’ to the file.

  1. Using fgetc() to Read Characters from a File: In this example, we’ll read characters from a file named “input.txt” using fgetc() and print them to the console.
   #include <stdio.h>

   int main() {
       FILE *filePtr;
       int ch;

       // Open a file for reading
       filePtr = fopen("input.txt", "r");

       if (filePtr == NULL) {
           perror("Error opening file");
           return 1;
       }

       // Read characters from the file and print them
       while ((ch = fgetc(filePtr)) != EOF) {
           putchar(ch);
       }

       // Close the file
       fclose(filePtr);

       printf("\nCharacters read from the file.\n");

       return 0;
   }

This program opens “input.txt” in read mode, reads characters from the file, and prints them to the console. It continues reading until it reaches the end of the file (EOF).

Advantages of fputc() fgetc() in C Language

fputc() and fgetc() in the C programming language offer several advantages for character-based input and output operations with files:

  1. Simplicity: fputc() and fgetc() are simple and easy to use. They provide a straightforward way to perform character-level I/O operations, making them suitable for basic file operations.
  2. Character-by-Character Handling: These functions allow you to work with files on a character-by-character basis, which can be useful when dealing with simple text files or when you need fine-grained control over file content.
  3. Low Overhead: Compared to more complex file I/O functions like fprintf() and fscanf(), fputc() and fgetc() have lower overhead, making them efficient for handling individual characters or small amounts of data.
  4. Compatibility with Text Files: They are well-suited for reading and writing plain text files, such as configuration files, log files, and simple data files.
  5. Minimal Data Conversion: Since these functions operate at the character level, there is minimal data conversion or formatting involved. They work directly with character data as it appears in the file.
  6. Sequential Access: fgetc() reads characters sequentially from the file, allowing you to process data sequentially without the need for complex seek operations.
  7. Integration with Standard Input/Output: These functions work with file streams, which means you can easily switch between reading from a file and reading from the standard input (keyboard) or writing to the standard output (console).
  8. Portability: fputc() and fgetc() are part of the C Standard Library, making code that uses these functions highly portable across different platforms and C compilers.
  9. Minimal Resource Usage: These functions are lightweight in terms of resource usage, making them suitable for resource-constrained environments, such as embedded systems.
  10. Error Handling: They return specific error codes (e.g., EOF for end-of-file or an error code for other errors) that allow you to handle error conditions effectively.
  11. Character Manipulation: You can perform character-level manipulations, such as filtering, transforming, or encrypting characters, easily using these functions.
  12. Educational Purposes: fputc() and fgetc() are often used in educational contexts to teach students the fundamentals of file I/O and character-level operations.

Disadvantages of fputc() fgetc() in C Language

While fputc() and fgetc() have their advantages, they also come with certain disadvantages and limitations that developers should be aware of:

  1. Limited to Character-Level I/O: fputc() and fgetc() are designed for character-level input and output. They are not suitable for handling complex data structures, such as binary data or structured records. For such tasks, you would need to implement custom serialization and deserialization.
  2. Inefficiency for Large Files: When working with large files or processing a significant amount of data, these functions may result in relatively inefficient I/O operations, as they handle data one character at a time.
  3. Text Encoding Challenges: When working with character encoding other than the system’s default (e.g., UTF-8 or UTF-16), character conversion and encoding mismatches can be problematic, as these functions do not handle encoding transformations.
  4. Lack of Formatting: Unlike functions like fprintf() and fscanf(), fputc() and fgetc() do not support formatting or structured data representation. They work with raw character data without regard to formatting, which can make it challenging to work with structured data.
  5. String Handling Complexity: Reading or writing strings with these functions can be more complex, as you need to handle null-terminated strings manually. There is no built-in mechanism to read or write entire strings as a unit.
  6. File Size and Memory Constraints: These functions do not handle large files or memory-mapped files efficiently. For scenarios where files are too large to fit into memory, alternative methods should be considered.
  7. Error Handling Complexity: While these functions provide error reporting through EOF and specific error codes, handling and interpreting errors can be more complex compared to higher-level I/O functions.
  8. Seek and Random Access Limitations: These functions read data sequentially from the file, making it challenging to perform random access or seek operations to specific file positions efficiently.
  9. Buffering and Performance: These functions do not take advantage of internal buffering mechanisms, which can lead to suboptimal performance when reading or writing small amounts of data.
  10. Security Concerns: Mishandling input or output data with these functions can introduce security vulnerabilities, such as buffer overflows or injection attacks, if not handled carefully.
  11. Platform-Specific Behavior: While the functions themselves are standardized, their behavior, particularly concerning line endings (e.g., newline characters), can vary across different platforms and operating systems.
  12. Not Suitable for Binary Data: fputc() and fgetc() are primarily intended for text data. When working with binary data, these functions may not preserve binary integrity, leading to data corruption.

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading