C fgets() function

C library function - fgets()

The fgets() function is used to read characters 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 characters read is equal to n-1, whichever comes first. fgets() stores the result in a string and ends it with a null character (/0). A new-line character is included in the string if it is read. The string is empty if n equals 1.


char *fgets(char *str, int n, FILE *stream)


Name Description
str This is the variable in which the string will be stored
n This is the maximum length of the string to be read
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream.

Return value

  • Upon successful completion, fgets() shall return s. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer.
  • If a read error occurs, the error indicator for the stream shall be set, fgets() shall return a null pointer, and shall set errno to indicate the error.

Example: Using fgets(), read data from a file

int main()
    char string[20];
    FILE *fp;
    // Write some text in test.txt
    char str[] = "C programming tutorial.";
    fp = fopen( "test.txt" , "w" );
    fwrite(str , 1 , sizeof(str) , fp );
    fclose(fp) ;
	// Here fgets() function is used to read text fine from a file.	
    printf("The string is: %s",string);
    return 0;
The string is: C programming tutorial.

Example: Using fgets(), read from stdin

int main()
    char text[50];
    printf("Input a string: ");
    printf("\nThe string is: %s",text);
    return 0;
Input a string: C Programming

The string is: C Programming

C Programming Code Editor:

Previous C Programming: C fgetc()
Next C Programming: C fputc()

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

Ref : https://bit.ly/3pdEk6f