Tutorial

fgets() and gets() in C Programming

Published on August 3, 2022
Default avatar

By Sneh

fgets() and gets() in C Programming

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Introduction

We all are familiar with the scanf() function. It is the main function applicable to take basic user inputs. Even though scanf() works great while taking inputs such as integer, character, float etc. It certainly falls behind while taking string inputs containing whitespaces. Let’s take a look at an example,

#include<stdio.h>
int main()
{
    char string[10];
    printf("Enter the string: ");
    scanf("%s", string);
    printf("\n %s",string);
    return 0;
}

Output:

Problem With Scanf
Problem With scanf()

As we can observe from the above example. scanf() stops scanning as soon as it encounters whitespace or newline. This, in fact, makes taking string inputs using scanf() a bit troublesome. This can be easily avoided by using some other input functions like gets() and fgets().

In this article, we are going to learn how to apply both the functions and compare them side by side.

gets() function in C

gets() is a pre-defined function in C which is used to read a string or a text line. And store the input in a well-defined string variable. The function terminates its reading session as soon as it encounters a newline character.

Syntax:

gets( variable name );

The given code below illustrates the use of the gets() function,

#include<stdio.h>
int main()
{
    char string[10];
    printf("Enter the String: ");
    gets(string);
    printf("\n%s",string);
    return 0;
}

Output:

Use Of Gets()
Use Of Gets

Compare the output with the one while using scanf(). ‘Hello World’ is now treated as a single string.

fgets() function in C

The standard C library also provides us with yet another function, the fgets() function. The function reads a text line or a string from the specified file or console. And then stores it to the respective string variable.

Similar to the gets() function, fgets also terminates reading whenever it encounters a newline character. But furthermore, unlike gets(), the function also stops when EOF is reached or even if the string length exceeds the specified limit, n-1.

Syntax,

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

  • str - It is the variable in which the string is going to be stored
  • n - It is the maximum length of the string that should be read
  • stream - It is the filehandle, from where the string is to be read.

Fortunately, we can both read text lines from a file or the standard input stream by using the fgets() function. Let us see how

1. Read from a given file using fgets()

For example,

#include<stdio.h>
int main()
{
    char string[20];
    FILE *fp;
    fp=fopen("file.txt","r");
    fgets(string,20,fp);
    printf("The string is: %s",string);
    fclose(fp);
    return 0;
}
    

Consider file.txt to contain the line ‘JournalDev fgets() example!’. In that case, the output of the above code would be,

Fgets Output
fgets() file input

2. Read from stdin using fgets()

#include<stdio.h>
int main()
{
    char string[20];
    printf("Enter the string: ");
    fgets(string,20,stdin);         #input from stdin stream
    printf("\nThe string is: %s",string);
    return 0;
}

Output:

Fgets() Stdin Input
fgets() Stdin Input

Conclusion

Even though both the functions, gets() and fgets() can be used for reading string inputs. The biggest difference between the two is the fact that the latter allows the user to specify the buffer size. Hence it is highly recommended over the gets() function.

The gets() function doesn’t have the provision for the case if the input is larger than the buffer. As a result, memory clogging may occur. This is the part where the fgets() function shines and provides an ultimate solution.

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Sneh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 13, 2020

Hy, ty for article. One comment: “fgets(string,20,fp);” reads the first 19+“\0” characters, so the result should be: "JournalDev fgets() ". Br

- Adi

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel