fgets() in C - Source Code Example

In this source code example, we will see how to use the fgets() function in C programming with an example.

fgets() Function Overview

The fgets() function in C is used to read a line from a given file or input stream. It reads lines of text until a newline or EOF is found, or until a certain number of characters have been read.

Source Code Example

#include <stdio.h>

int main() {
    FILE *filePtr;
    char buffer[100];  // Buffer to store the read line

    // Open file for writing and add content
    filePtr = fopen("sample.txt", "w");
    if (!filePtr) {
        printf("Error opening file.\n");
        return 1;
    }
    fputs("Hello, Ram!\n", filePtr);
    fputs("How are you today?", filePtr);
    fclose(filePtr);

    // Open file for reading
    filePtr = fopen("sample.txt", "r");
    if (!filePtr) {
        printf("Error opening file.\n");
        return 1;
    }

    // Read and print the first line
    printf("Reading first line:\n");
    if (fgets(buffer, sizeof(buffer), filePtr)) {
        printf("%s", buffer);
    }

    // Read and print the second line
    printf("\nReading next line:\n");
    if (fgets(buffer, sizeof(buffer), filePtr)) {
        printf("%s", buffer);
    }

    // Close the file
    fclose(filePtr);

    return 0;
}

Output

Reading first line:
Hello, Ram!

Reading next line:
How are you today?

Explanation

1. We first create a file and write two lines into it.

2. We then open this file to read.

3. The fgets() function is used to read the first line, and then it's used again for the second line.

4. In the end, we close the file.

Note: fgets() stops reading at a newline character, at the end-of-file, or after reading a set number of characters, whichever comes first.


Comments