How to use the 'fgets' function in C?

In C programming, handling input from users or external files is a common task. The fgets function plays a crucial role in reading strings, including spaces, from a specified stream.

In this comprehensive guide, we will delve into the details of the fgets function, understand its syntax, usage, and explore some practical examples.

Table of Contents #

  1. Introduction to fgets
  2. Using fgets for Keyboard Input
  3. Using fgets for File Input
  4. Handling Newline Characters
  5. Conclusion

Introduction to "fgets"

The fgets function is used to read a string from a specified stream (typically a file or standard input) up to a specified number of characters or until a newline character ('\n') is encountered, whichever comes first.

This function is part of the C Standard Library (stdio.h), making it a standard and portable way to handle string input.

Syntax:

char *fgets(char *str, int size, FILE *stream);

Return Value:

Using fgets for Keyboard Input

Let's start with a basic example demonstrating the use of fgets to get input from the keyboard:

#include <stdio.h>

int main() {
    char buffer[100]; // Buffer to store the input string

    // Prompt the user for input
    printf("Enter a string: ");

    // Use fgets to read input from standard input (keyboard)
    if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        // Print the input string
        printf("You entered: %s", buffer);
    } else {
        printf("Error reading input.\n");
    }

    return 0;
}

In this example:

Using fgets for File Input

The fgets function is also commonly used for reading strings from files. Here's an example of reading lines from a file:

#include <stdio.h>

int main() {
    FILE *file = fopen("sample.txt", "r"); // Open the file for reading
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    char buffer[100];

    // Read and print each line from the file
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Line from file: %s", buffer);
    }

    // Close the file
    fclose(file);

    return 0;
}

In this example:

Handling Newline Characters

One thing to note is that fgets includes the newline character ('\n') in the string if it is encountered before reaching the specified size.

To remove the newline character, you can use the strcspn function:

#include <stdio.h>
#include <string.h>

int main() {
    char buffer[100];

    printf("Enter a string: ");
    if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        // Remove the newline character if present
        buffer[strcspn(buffer, "\n")] = '\0';

        printf("You entered: %s\n", buffer);
    } else {
        printf("Error reading input.\n");
    }

    return 0;
}

In this example, strcspn(buffer, "\n") returns the position of the newline character in the string, and we replace it with the null-terminator ('\0').

Conclusion

The fgets function in C is a versatile tool for handling string input from various sources.

Whether you're reading input from the keyboard or processing data from files, understanding how to use fgets is crucial. This guide has covered the syntax, usage, and practical examples of the fgets function.

Incorporating this knowledge into your C programming skills will enable you to effectively handle string input in a variety of scenarios.