Syntax
#include <stdio.h> char *fgets (char *string, int n, FILE *stream);Description
fgets reads bytes from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of bytes read is equal to n-1, whichever comes first. fgets stores the result in string and adds a null character (\0) to the end of the string. The string includes the new-line character, if read. If n is equal to 1, the string is empty.
fgets returns a pointer to the string buffer if successful. A NULL return value indicates an error or an end-of-file condition. Use feof or ferror to determine whether the NULL value indicates an error or the end of the file. In either case, the value of the string is unchanged.
This example gets a line of input from a data stream. The example reads no more than MAX_LEN - 1 characters, or up to a new-line character, from the stream.
#include <stdio.h> #define MAX_LEN 100 int main(void) { FILE *stream; char line[MAX_LEN],*result; stream = fopen("myfile.dat", "rb"); if ((result = fgets(line, MAX_LEN, stream)) != NULL) printf("The string is %s\n", result); if (fclose(stream)) perror("fclose error"); return 0; /**************************************************************************** If myfile.dat contains: This is my data file. The output should be: The string is This is my data file. ****************************************************************************/ }Related Information