std::fgets (3) - Linux Manuals

std::fgets: std::fgets


std::fgets - std::fgets


Defined in header <cstdio>
char* fgets( char* str, int count, std::FILE* stream );

Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str. Reading stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character. If no errors occur, writes a null character at the position immediately after the last character written to str.


str - pointer to an element of a char array
count - maximum number of characters to write (typically the length of str)
stream - file stream to read the data from

Return value

str on success, null pointer on failure.
If the failure has been caused by end-of-file condition, additionally sets the eof indicator (see std::feof()) on stream. The contents of the array pointed to by str are not altered in this case.
If the failure has been caused by some other error, sets the error indicator (see std::ferror()) on stream. The contents of the array pointed to by str are indeterminate (it may not even be null-terminated).


// Run this code

  #include <iostream>
  #include <cstdio>
  #include <cstdlib>

  int main()
      std::FILE* tmpf = std::tmpfile();
      std::fputs("Alan Turing\n", tmpf);
      std::fputs("John von Neumann\n", tmpf);
      std::fputs("Alonzo Church\n", tmpf);

      char buf[8];
      while (std::fgets(buf, sizeof buf, tmpf) != NULL) {
          std::cout << '"' << buf << '"' << '\n';


  "Alan Tu"
  "John vo"
  "n Neuma"
  "Alonzo "

See also

scanf reads formatted input from stdin, a file stream or a buffer
fscanf (function)

gets reads a character string from stdin
(deprecated in C++11)
(removed in C++14)
                      writes a character string to a file stream
fputs (function)