fgets() Function

The fgets() function in C reads a line of text from a given stream into a character array. It stops reading when either (num-1) characters have been read, a newline is encountered, or the end-of-file is reached, and it automatically appends a null character to terminate the string.


Syntax of fgets()

</>
Copy
char *fgets(char *str, int num, FILE *stream);

Parameters

ParameterDescription
strPointer to an array of chars where the read string will be stored.
numMaximum number of characters to read (including the terminating null character).
streamPointer to a FILE object that identifies the input stream (for example, stdin for standard input).

Unlike the deprecated gets() function, fgets() limits the number of characters read, thus helping to prevent buffer overflows. Additionally, it retains the newline character if it is encountered before reaching the limit.

Return Value

On success, fgets() returns the pointer to the string (str). If the end-of-file is encountered before any characters are read or if a read error occurs, it returns a null pointer, with the appropriate indicators set (feof or ferror).


Examples for fgets()

Example 1: Reading a Line from Standard Input

This example demonstrates the basic usage of fgets() to read a line from the standard input (keyboard) and display it.

Program

</>
Copy
#include <stdio.h>

int main() {
    char buffer[100];

    printf("Enter a line of text: ");
    if (fgets(buffer, 100, stdin) != NULL) {
        printf("You entered: %s", buffer);
    } else {
        printf("Error reading input.\n");
    }
    
    return 0;
}

Explanation:

  1. An array buffer is declared to hold the input string.
  2. The program prompts the user to enter a line of text.
  3. fgets() reads up to 99 characters from stdin (leaving room for the null terminator) and stores them in buffer.
  4. The entered string is then printed to the console.

Program Output:

Enter a line of text: Hello, World!
You entered: Hello, World!

Example 2: Reading a Line from a File

This example shows how to use fgets() to read a line from a file and then print it.

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp = fopen("sample.txt", "r");
    char line[150];

    if (fp == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }

    if (fgets(line, sizeof(line), fp) != NULL) {
        printf("Read line: %s", line);
    } else {
        printf("No data read from file.\n");
    }

    fclose(fp);
    return 0;
}

Explanation:

  1. The file sample.txt is opened for reading.
  2. An array line is allocated to store the read string.
  3. fgets() reads a line from the file and stores it in line.
  4. If successful, the line is printed; otherwise, an error message is displayed.
  5. The file is then closed to free up resources.

Program Output:

Read line: This is a sample line from the file.

Example 3: Handling End-of-File or Read Error

This example demonstrates how to handle cases where fgets() returns a null pointer due to end-of-file or a read error.

Program

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    char buffer[50];

    /* Simulate reading from an empty file by using a closed stream */
    FILE *fp = fopen("empty.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }

    /* Read until fgets returns NULL */
    if (fgets(buffer, sizeof(buffer), fp) == NULL) {
        printf("No data read (end-of-file or read error encountered).\n");
    } else {
        printf("Data: %s", buffer);
    }

    fclose(fp);
    return 0;
}

Explanation:

  1. The program attempts to open a file named empty.txt for reading.
  2. If the file opens successfully but contains no data, fgets() will return a null pointer.
  3. The program then prints a message indicating that no data was read due to reaching the end-of-file or encountering a read error.
  4. Finally, the file is closed properly.

Program Output:

No data read (end-of-file or read error encountered).