fputs() fgets() in C Language

Understanding of fputs() fgets() 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

ef="https://en.wikipedia.org/wiki/C_(programming_language)#">C: fputs() and fgets(). These functions allow you to write and read strings from a file, respectively. Let’s see how they work and why they are so handy!

What is a fputs() fgets() in C Language?

In the C programming language, fputs() and fgets() are library functions used for reading and writing text to and from files, respectively. They are typically used when working with text files in C.

  1. fputs():
  • fputs() stands for “file puts” and is used to write a string to a specified file stream.
  • Its syntax is: int fputs(const char *str, FILE *stream);
  • str is the string you want to write to the file.
  • stream is a pointer to the file stream where you want to write the string.
  • It returns a non-negative value if successful and EOF (end-of-file) if there’s an error.

Example:

#include <stdio.h>

int main() {
    FILE *file;
    file = fopen("example.txt", "w");
    if (file != NULL) {
        fputs("Hello, fputs!", file);
        fclose(file);
    } else {
        printf("Failed to open the file.\n");
    }
    return 0;
}
  1. fgets():
  • fgets() stands for “file gets” and is used to read a line of text from a specified file stream.
  • Its syntax is: char *fgets(char *str, int n, FILE *stream);
  • str is a character array where the read line will be stored.
  • n is the maximum number of characters to read (typically the size of the character array).
  • stream is a pointer to the file stream from which you want to read.
  • It returns str if successful and NULL on failure or when the end of the file is reached.

Example:

#include <stdio.h>

int main() {
    FILE *file;
    char buffer[100];

    file = fopen("example.txt", "r");
    if (file != NULL) {
        while (fgets(buffer, sizeof(buffer), file) != NULL) {
            printf("Read: %s", buffer);
        }
        fclose(file);
    } else {
        printf("Failed to open the file.\n");
    }
    return 0;
}

Examples of fputs() fgets() in C Language?

Here are examples of using fputs() and fgets() in C to write and read text from a file:

  1. Using fputs() to Write to a File:
#include <stdio.h>

int main() {
    FILE *file;
    file = fopen("example.txt", "w"); // Open the file in write mode

    if (file != NULL) {
        char text[] = "This is a sample text.\nHello, fputs!";

        if (fputs(text, file) != EOF) {
            printf("Text successfully written to the file.\n");
        } else {
            printf("Error writing to the file.\n");
        }

        fclose(file);
    } else {
        printf("Failed to open the file.\n");
    }

    return 0;
}
  1. Using fgets() to Read from a File:
#include <stdio.h>

int main() {
    FILE *file;
    char buffer[100];

    file = fopen("example.txt", "r"); // Open the file in read mode

    if (file != NULL) {
        while (fgets(buffer, sizeof(buffer), file) != NULL) {
            printf("Read: %s", buffer);
        }

        fclose(file);
    } else {
        printf("Failed to open the file.\n");
    }

    return 0;
}

Advantages of fputs() fgets() in C Language

The fputs() and fgets() functions in the C programming language offer several advantages for working with text files:

  1. Simplicity: Both functions are relatively simple to use, making them accessible for beginners and experienced programmers alike. They provide a straightforward way to read from and write to text files.
  2. Portability: fputs() and fgets() are part of the C standard library, which means they are available on virtually all C compilers and platforms. This makes your code portable across different systems without modification.
  3. Buffered I/O: These functions provide buffered I/O, which means they read or write data in chunks rather than one character at a time. This can significantly improve the performance of your file I/O operations, especially when dealing with large files.
  4. Line-Oriented: fgets() is particularly useful for reading lines of text from a file. It automatically stops reading when it encounters a newline character ('\n'), allowing you to process files line by line.
  5. Error Handling: Both functions provide error handling through their return values. They return NULL or EOF in case of an error, making it easy to check for and handle errors in your file operations.
  6. Text Mode Handling: fgets() and fputs() are designed for text files. They automatically handle newline characters correctly, translating them between the platform-specific newline representations (e.g., \n on Unix-like systems and \r\n on Windows).
  7. Memory Management: fgets() reads data into a character array you provide, allowing you to control memory allocation. This can help prevent buffer overflows and memory-related issues.
  8. Compatibility with Standard I/O Functions: These functions work seamlessly with other standard I/O functions like fprintf(), fscanf(), printf(), and scanf(), allowing you to build complex file processing pipelines using the C standard library.
  9. Human-Readable Code: The use of fputs() and fgets() makes your code more human-readable because it clearly indicates the intention of reading from or writing to a file.

Disadvantages of fputs() fgets() in C Language

While fputs() and fgets() in C have their advantages, they also come with some limitations and potential disadvantages, especially when compared to other file I/O methods:

  1. Text-Only Handling: fputs() and fgets() are designed for text file handling. If you need to work with binary files or perform low-level file operations, they may not be suitable.
  2. Line Length Limitation: fgets() reads data line by line, and it’s limited by the size of the character array you provide as a buffer. If you have long lines or lines longer than your buffer size, you’ll need to handle line continuation and merging manually.
  3. Inefficient for Large Files: For very large files, reading or writing line by line with fgets() and fputs() can be inefficient, as it involves many system calls. More efficient methods like memory-mapped files or reading/writing in larger chunks may be preferable.
  4. Buffer Management: You need to manage the buffer size yourself when using fgets(). If the buffer is too small to hold a complete line, you risk truncating the data. On the other hand, if the buffer is too large, it may be wasteful in terms of memory usage.
  5. Platform-Specific Newline Handling: While fgets() and fputs() handle newline characters in text files, the exact handling depends on the platform. This can lead to compatibility issues if you need to process files across different systems with different newline conventions (e.g., \n on Unix-like systems and \r\n on Windows).
  6. Limited Error Handling: While these functions return NULL or EOF on error, the error information is limited. You might not get detailed information about the cause of the error, making it challenging to diagnose and handle issues.
  7. Not Ideal for Complex Parsing: If you need to perform complex parsing of structured data within a file (e.g., parsing CSV or XML files), fgets() may not be the most suitable choice. Specialized parsing libraries or regular expressions might be more appropriate.
  8. No Random Access: fgets() and fputs() are sequential file access functions, meaning you can’t easily jump to a specific position in the file or overwrite specific parts of the file without additional logic.
  9. Performance Overhead: The use of fgets() and fputs() introduces some performance overhead due to the buffering mechanism, which may not be significant for most applications but could matter in certain high-performance scenarios.

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