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()

Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

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