C++ fgets()

The fgets() function in C++ reads a specified maximum number of characters from the given file stream.

fgets() prototype

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

The fgets() function reads a maximum of count-1 characters from the given file stream and stores them in the array pointed to by str.

The parsing continues until the end of file occurs or a newline character (\n) is found. The array str will contain the newline character too in case it is found. If no error occurs, a null character is written at the end of str.

It is defined in <cstdio> header file.

fgets() Parameters

  • str: Pointer to an character array that stores the content of file.
  • count: Maximum number of characters to write.
  • stream: The file stream to read the characters.

fgets() Return value

  • On success, the fgets() function returns str and on failure it returns null pointer.
  • If the failure is caused due to end of file condition, it sets the eof indicator. In this case, the contents of str are not changed.
  • If the failure is caused due to some other error, it sets the error indicator. In this case, the contents of str are indeterminate. They may not even be null terminated.

Example: How fgets() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int count = 10;
    char str[10];
    FILE *fp;
    
    fp = fopen("file.txt","w+");
    fputs("An example file\n", fp);
    fputs("Filename is file.txt\n", fp);
    
    rewind(fp);
    
    while(feof(fp) == 0)
    {
        fgets(str,count,fp);
        cout << str << endl;
    }
    
    
    fclose(fp);
    return 0;
}

When you run the program, a possible output will be:

An exampl
e file

Filename
is file.t
xt