Share this page

# fgets

Input-Output Functions

Reads a string from a file.

    char *fgets( char *string, int maxchar, FILE *file_pointer);

string | The string to retrieve.
maxchar | The maximum number of characters to retrieve.
file_pointer | A pointer to a file.

## Return Values

Upon success, it returns the read string. If the End Of File is reached or if a reading error occurred, it returns a null pointer.

## Example

The following example, for Windows platforms, opens a file and reads the first line using fgets.

To run the example, copy the file readme.txt from the installation's dat directory to the c drive, or copy another file and change the value of filename.

Copy code

    #include <stdio.h>
        int i, total = 0;
        char line[100], ch;
        FILE* file_stream;
        char *filename = "c:\\readme.txt";
        if ((file_stream = fopen(filename, "r")) == NULL ) {
            lr_error_message("Cannot open %s", filename);
            return -1;
        }
        // Get the first line from the file
        if (fgets(line, 100, file_stream) == NULL)
            lr_output_message("fgets error");
        else
            lr_output_message( "The first line is \"%s\"", line);
        if (fclose(file_stream))
            lr_error_message("Error closing file %s", filename);

    Example:
                    Output:
    The first line is "**** For an HTML version of the ReadMe file, see readme.htm ****"

Tips to improve your search results... VuGen Function Reference Version 26.1-26.3 Function Reference 26.1-26.3 All View Local Help Center View Online Help Center Version: