fgets() function in C++

In this guide, you will learn what is fgets() function is in C++ programming and how to use it with an example.

1. fgets() Function Overview

The fgets() function is used to read a string from the specified stream into an array. It stops reading either after an EOF (End Of File) is encountered, a newline character is read, or the specified number of characters minus one have been read, whichever comes first. The string read by fgets() includes the newline character, if one was found.

Signature:

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

Parameters:

- str: A pointer to an array of chars where the read string will be stored.

- num: Maximum number of characters to be read (including the terminating null character).

- stream: Pointer to a FILE object that specifies an input stream.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    FILE* fp;
    char str[100];

    // Open file in read mode
    fp = fopen("test.txt", "r");
    if(fp == NULL) {
        std::cerr << "Error opening file.";
        return 1;
    }

    // Using fgets to read the file
    while(fgets(str, sizeof(str), fp) != NULL) {
        std::cout << str;
    }

    // Close the file
    fclose(fp);

    return 0;
}

Output:

[This will display the content of "test.txt", so the exact output will depend on what's inside that file.]

3. Explanation

1. We start by declaring a FILE pointer fp and a character array str with a size of 100.

2. We then open the file "test.txt" in read mode.

3. If the file is successfully opened, we use fgets() inside a while loop to read the file line by line.

4. The read line is then displayed to the standard output.

5. After reading the entire file, we close it using fclose().


Comments