w3resource

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.

Syntax:

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

Parameters:

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

#include<stdio.h>
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.	
	  fp=fopen("test.txt","r");
    fgets(string,30,fp);
    printf("The string is: %s",string);
    fclose(fp);
    return 0;
}
The string is: C programming tutorial.

Example: Using fgets(), read from stdin

#include<stdio.h>
int main()
{
    char text[50];
    printf("Input a string: ");
    fgets(text,50,stdin);
    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()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/stdio/c_library_method_fgets.php