##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::fgets

From cppreference.com
< cpp‎ | io‎ | c

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

Reads at most count - 1 characters from the given file stream and stores them in `str`. The produced character string is always null-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case `str` will contain that newline character.

### [edit] Parameters

str | - | string to read the characters to
count | - | the length of `str`
stream | - | file stream to read the data from

### [edit] Return value

`str` on success, NULL on failure.

If the failure has been caused by end of file condition, additionally sets the eof indicator (see std::feof()) on stdin. If the failure has been caused by some other error, sets the error indicator (see std::ferror()) on stdin.

### [edit] Example

Run this code

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

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

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

Output:

    "Alan Tu"
    "ring
    "
    "John vo"
    "n Neuma"
    "nn
    "
    "Alonzo "
    "Church
    "

### [edit] See also

scanf fscanf sscanf | reads formatted input from stdin, a file stream or a buffer (function) [edit]
gets | reads a character string from stdin (function) [edit]
fputs | writes a character string to a file stream (function) [edit]
C documentation for fgets

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/io/c/fgets&oldid=65792"