The Wayback Machine - https://web.archive.org/web/20240913200135/https://www.geeksforgeeks.org/fgets-gets-c-language/
Open In App

fgets() and gets() in C language

Last Updated : 06 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets().

fgets()

The fgets() reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

Syntax

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

Parameters

  • str: Pointer to an array of chars where the string read is copied.
  • n: Maximum number of characters to be copied into str (including the terminating null character).
  • *stream: Pointer to a FILE object that identifies an input stream.

Note: stdin can be used as argument to read from the standard input.

Return Value

  • The fgets() function returns a pointer to the string where the input is stored.

Features of fgets()

  • It follows some parameters such as Maximum length, buffer, and input device reference.
  • It is safe to use because it checks the array bound.
  • It keeps on reading until a new line character is encountered or the maximum limit of the character array.

Example of fgets()

Let’s say the maximum number of characters is 15 and the input length is greater than 15 but still fgets() will read only 15 characters and print it. 

C




// C program to illustrate fgets()
#include <stdio.h>
#define MAX 15
 
int main()
{
    // defining buffer
    char buf[MAX];
 
    // using fgets to take input from stdin
    fgets(buf, MAX, stdin);
    printf("string is: %s\n", buf);
 
    return 0;
}


Since fgets() reads input from the user, we need to provide input during runtime.

Input:
Hello and welcome to GeeksforGeeks

Output:
string is: Hello and welc

gets()

Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.

  • It is not safe to use because it does not check the array bound.
  • It is used to read strings from the user until a newline character is not encountered.

Syntax

char *gets( char *str );

Parameters

  • str: Pointer to a block of memory (array of char) where the string read is copied as a C string.

Return Value

  • The function returns a pointer to the string where input is stored.

Example of gets()

Suppose we have a character array of 15 characters and the input is greater than 15 characters, gets() will read all these characters and store them into a variable. Since, gets() does not check the maximum limit of input characters, at any time compiler may return buffer overflow error. 

C++




// C program to illustrate
// gets()
#include <stdio.h>
#define MAX 15
 
int main()
{
    // defining buffer
    char buf[MAX];
 
    printf("Enter a string: ");
 
    // using gets to take string from stdin
    gets(buf);
    printf("string is: %s\n", buf);
 
    return 0;
}


Since gets() reads input from the user, we need to provide input during runtime.

Input:
Hello and welcome to GeeksforGeeks

Output:
Hello and welcome to GeeksforGeeks

Conclusion

Both fgets() and gets() functions can be used for reading string input from standard input. The main difference between fgets() function and gets() function is that fgets() function allows the user to specify the maximum number of characters to read and we can also change the input stream to any file in fgets().



Previous Article
Next Article

Similar Reads

Problem With Using fgets()/gets()/scanf() After scanf() in C
scanf() is a library function in C. It reads standard input from stdin. fgets() is a library function in C. It reads a line from the specified stream and stores it into the string pointed to by the string variable. It only terminates when either: end-of-file is reachedn-1 characters are readthe newline character is read 1) Consider a below simple p
3 min read
Difference between scanf() and gets() in C
scanf()It is used to read the input(character, string, numeric data) from the standard input(keyboard).It is used to read the input until it encounters a whitespace, newline or End Of File(EOF). For example see the following code: C/C++ Code // C program to see how scanf() // stops reading input after whitespaces #include &amp;lt;stdio.h&amp;gt; in
3 min read
gets() is risky to use!
Consider the below program. C/C++ Code void read() { char str[20]; gets(str); printf(&quot;%s&quot;, str); return; } The code looks simple, it reads string from standard input and prints the entered string, but it suffers from Buffer Overflow as gets() doesn't do any array bound testing. gets() keeps on reading until it sees a newline character. To
2 min read
scanf("%[^\n]s", str) Vs gets(str) in C with Examples
gets()gets is a more convenient method of reading a string of text containing whitespaces.Unlike scanf(), it does not skip whitespaces.It is used to read the input until it encounters a new line.%[^\n]It is an edit conversion code.The edit conversion code %[^\n] can be used as an alternative to gets.C supports this format specification with scanf()
2 min read
Difference Between C Language and LISP Language
C Language: C is the procedural Programming language. It was designed to be compiled using a compiler. The Language has small and fixed number of keywords like if/else, for, while,.. etc. We can use more than one assignment that may be used in one statement in this language. Functions are also used here, it can return values that can be ignored, wh
2 min read
Similarities and Differences between Ruby and C language
Similarities between Ruby and C There are many similarities between C and Ruby, and some of them are: Like C, in Ruby also… A programmer is able to program procedurally if they like to do. But still, behind the scenes, it will be object-oriented.Both the languages have the same operators, for example, compound assignment and bitwise operators. But
3 min read
Difference between Java and C language
Here are some of the differences between Java and C language. C is much faster than Java Java is slower than C due to overhead. C Java C was developed by Dennis M. Ritchie between 1969 and 1973.Java was developed by James Gosling in 1995.C is a Procedural Programming Language.Java is Object-Oriented language.C is more procedure-oriented.Java is mor
3 min read
Difference between %d and %i format specifier in C language
A format specifier is a special character or sequence of characters used to define the type of data to be printed on the screen or the type of data to be scanned from standard input. A format specifier begins with a '%' character followed by the sequence of characters for different types of data. In short, it tells us which type of data to store an
3 min read
lvalue and rvalue in C language
lvalue:- lvalue simply means an object that has an identifiable location in memory (i.e. having an address). In any assignment statement "lvalue" must have the capability to store the data.lvalue cannot be a function, expression (like a+b) or a constant (like 3 , 4 , etc.). L-value: "l-value" refers to memory location which identifies an object. l-
4 min read
Difference between while(1) and while(0) in C language
Prerequisite: while loop in C/C++ In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The boolean condition is either true or false. while(1) It is an infinite loop which will run till a break statement is issued explicitly. Interestingly not
3 min read
Difference Between Matlab and C Language
Matlab and C are both powerful programming languages but they serve different purposes and have distinct features. In this article, we will learn the fundamental differences between Matlab and the C language. MATLABMATLAB stands for Matrix Laboratory and is a high-level programming language primarily used for numerical computing such as matrix mani
3 min read
isxdigit() function in C Language
isxdigit() function in C programming language checks that whether the given character is hexadecimal or not. isxdigit() function is defined in ctype.h header file. Hexadecimal equivalent of Decimal Numbers: Hexadecimal: 0 1 2 3 4 5 6 7 8 9 A B C D E F Decimal: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Syntax: char isxdigit( char x); Examples: Input : A
2 min read
isupper() function in C Language
isupper() function in C programming checks whether the given character is upper case or not. isupper() function is defined in ctype.h header file. Syntax : int isupper ( int x ); Examples: Input: A Output: Entered character is uppercase character Input: a Output: Entered character is not uppercase character Input: 1 Output: Entered character is not
2 min read
isalnum() function in C Language
isalnum() function in C programming language checks whether the given character is alphanumeric or not. isalnum() function defined in ctype.h header file. Alphanumeric: A character that is either a letter or a number. Syntax: int isalnum(int x); Examples: Input : 1 Output : Entered character is alphanumeric Input : A Output : Entered character is a
2 min read
trunc() , truncf() , truncl() in C language
All three functions are used to remove digits after decimal point and return the modified decimal number. trunc() : Truncates a double value after the decimal point and gives the integer part as the result. The return value and the arguments are of the type double. Syntax : double trunc(double x); Parameters: x :It takes a double value as an input
4 min read
How to clear console in C language?
It is one of the basic need a program may required i.e clear the console during execution time. Need of a clear console screen : A console screen must be cleared once its stated objectives have been completed. A user also needs a clear screen for new data. Like any other language, C offers a variety of ways to clear the console screen. The clear sc
7 min read
Assigning multiple characters in an int in C language
Consider the following C program. #include &lt;stdio.h&gt; int main(void) { int a = 'd'; printf(&quot;%d\n&quot;, a); /*OUTPUT - 100 (ASCII Code for character d)*/ int b = 'dd'; printf(&quot;%d&quot;, b); /*OUTPUT - 25700 (Explanation in detail given below)*/ return 0; } Output : 100 25700 We can easily guess that the output for 'd' is 100 as 100 i
1 min read
Introduction to the C99 Programming Language : Part I
Introduction: C99 is a standardized version of the C programming language that was published in 1999 by the International Organization for Standardization (ISO). It introduced a number of new features and improvements over the previous C89 standard, including support for variable-length arrays, flexible array members, complex numbers, and new keywo
8 min read
Introduction to the C99 Programming Language : Part II
In this article, we are going to discover some more interesting additions to C89 which gave us C99 standard: Variable Argument Lists: C99 brings out a small changes to the preprocessor. Macros can accept a variable number of arguments. These Macros are indicated by ellipsis (...) in their declaration. These Variable Arguments are represented by the
4 min read
Introduction to the C99 Programming Language : Part III
Kindly read Introduction to the C99 Programming Language (Part I) and Introduction to the C99 Programming Language (Part II) before reading this article. Addition of Library Functions: C99 provides some Additional Library functions listed below. Library Function Usage complex.h complex.h supports complex arithmetic fenv.h fenv.h gives access to flo
3 min read
Features of C Programming Language
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for sys
3 min read
Draw a smiley face using Graphics in C language
Prerequisite: graphics.h, How to include graphics.h in CodeBlocks? The task is to write a C program to draw a smiley face using graphics in C.To run the program we have the include the below header file: #include &lt;graphic.h&gt; Approach: We will create a Smiley Face with the help below functions: fillellipse(int x, int y, int x_radius, int y_rad
2 min read
Security issues in C language
C is a very powerful and popular programming language. It was first developed in the 1970s. C language is used in programming Network drivers, Interpreters, and Compilers, etc.Even though the C language is widely used in different systems still it has many security flaws associated with it. This article focuses on discussing security vulnerabilitie
12 min read
Shopping Cart Project Using C Language
Online Shopping applications are one of the favorite applications out of all online applications. It is a very much used application in everyone's life. So, Let's try to create a Shopping cart using C language which can perform basic tasks for us. The functionality of the Shopping Cart Although online Shopping has many functionalities we can't incl
11 min read
Test Cases For Signup Page Using C Language
Prerequisite: Structure in C In this article, we are going to check on how to check test cases for the signup page using C language. The signup page is where we enter data to create our account on any of the websites or applications. A test case is a document that contains various sets of data, conditions to be performed, and the expected result fo
6 min read
C Programming Language Standard
Introduction:The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the features that are still used in modern C programming, in
6 min read
A C Programming Language Puzzle
Give a = 12 and b = 36 write a C function/macro that returns 3612 without using arithmetic, strings and predefined functions. We strongly recommend you to minimize your browser and try this yourself first. Below is one solution that uses String Token-Pasting Operator (##) of C macros. For example, the expression "a##b" prints concatenation of 'a' a
1 min read
Signals in C language
Prerequisite : Fork system call, Wait system call A signal is a software generated interrupt that is sent to a process by the OS because of when user press ctrl-c or another process tell something to this process. There are fix set of signals that can be sent to a process. signal are identified by integers. Signal number have symbolic names. For ex
5 min read
kbhit in C language
kbhit() functionality is basically stand for the Keyboard Hit. This function is deals with keyboard pressing kbhit() is present in conio.h and used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file "conio.h". If a key has been pressed then it returns a non zero value otherwise re
2 min read
How to use POSIX semaphores in C language
Semaphores are very useful in process synchronization and multithreading. But how to use one in real life, for example say in C Language? Well, we have the POSIX semaphore library in Linux systems. Let's learn how to use it. The basic code of a semaphore is simple as presented here. But this code cannot be written directly, as the functions require
2 min read
Practice Tags :