In C programming language, fgets() and gets() are both functions used to read a string from input. However, there are some key differences between the two functions.
The gets() function reads a string from the standard input and stores it in the buffer pointed to by the argument. The function reads characters from the input until a newline character (
n) is encountered or until the maximum number of characters specified by the buffer size is reached. The newline character is replaced with a null character (
0) to terminate the string.
Here is an example of using the gets() function:
char str[50];
printf("Enter a string: ");
gets(str);
printf("You entered: %s", str);
In this example, the gets() function reads a string from the user and stores it in the str buffer. The resulting string is then printed to the console.
The gets() function has a major security issue, as it does not provide any bounds checking on the input. This can lead to a buffer overflow vulnerability if the user enters a string that is larger than the size of the buffer. For this reason, the use of gets() function is strongly discouraged.
The fgets() function, on the other hand, provides bounds checking and is considered a safer alternative to gets(). The syntax for the fgets() function is as follows:
char *fgets(char *str, int size, FILE *stream);
Here, str is a pointer to the buffer where the input string will be stored, size is the maximum number of characters to be read (including the newline and null characters), and stream is a pointer to the file object to be read from (usually stdin for standard input).
Here is an example of using the fgets() function:
char str[50];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s", str);
In this example, the fgets() function reads a string from the user and stores it in the str buffer. The sizeof() operator is used to ensure that the maximum number of characters to be read is equal to the size of the buffer. The resulting string is then printed to the console.
It is important to note that the fgets() function reads the newline character (
n) from the input and stores it in the buffer along with the string. This can be problematic if the newline character is not needed, as it can cause issues with string comparison and manipulation. To remove the newline character from the input string, the strcspn() function can be used, as shown in the following example:
char str[50];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "n")] = '0';
printf("You entered: %s", str);
In this example, the strcspn() function is used to find the position of the newline character in the input string and replace it with a null character (
0). The resulting string is then printed to the console without the newline character.