C Function Gets
Here is the English translation of the provided Chinese tutorial, keeping all code blocks and HTML tags intact:
[ C Standard Library - ](#)
* * *
In C language, `gets()` is a classic function used to read strings from standard input. While it's simple to use, security concerns should be noted.
The `gets()` function reads a line of string from **standard input stdin** and stores it in the specified character array. It reads characters until encountering a newline or end-of-file.
**Important Warning**: `gets()` has serious security vulnerabilities as it cannot specify buffer size, making it prone to buffer overflow. Therefore, in modern C programming, `fgets()` is a better alternative.
**Word Meaning**: `get` means "to obtain", and `s` stands for "string", together meaning "get string".
* * *
## Basic Syntax and Parameters
`gets()` is a function in the C standard library and requires including the header file ``.
### Syntax
char *gets(char *str);
### Parameter Description
* **Parameter**: `str`
* Type: `char *` (pointer to character array)
* Description: A pointer to a character array used to store the read C string. Ensure the array is large enough to hold the input string.
### Function Description
* **Return Value**: If successful, returns a pointer to `str`. If an error occurs or end-of-file is reached before reading any characters, returns `NULL`.
* **Effect**: The read string (excluding newline) is stored in the array pointed to by `str`, with a null character `` automatically appended at the end as the string terminator.
* * *
## Examples
Let's understand the usage of `gets()` through examples.
### Example 1: Basic Usage - Reading a String
## Example
#include
int main()
{
char str;
printf("Please enter a string: ");
gets(str);
printf("The string you entered is: %s", str);
return(0);
}
**Expected Output:**
Please enter a string: The string you entered is:
**Code Analysis:**
1. `#include ` is required to use the `gets()` function.
2. `char str;` defines a character array of length 50 to store the input string.
3. `gets(str);` reads a line of string from standard input and stores it in `str`.
4. `printf("The string you entered is: %s", str);` outputs the string using the `%s` format specifier.
### Example 2: Handling NULL Return Value
In practical programming, you should check the return value of `gets()` to handle potential errors.
## Example
#include
int main()
{
char str;
char*result;
printf("Please enter some content (press Ctrl+D to end):n");
result =gets(str);
if(result != NULL){
printf("Successfully read, content is:n%sn", str);
}else{
printf("Read failed or reached end-of-file!n");
}
return(0);
}
**Code Analysis:**
* `gets()` returns a pointer to the same string, or `NULL` on failure.
* When the user presses Ctrl+D (Linux/Mac) or Ctrl+Z (Windows), it triggers the end-of-file condition, causing `gets()` to return `NULL`.
* In real projects, it's recommended to use the safer `fgets()` instead of `gets()`.
### Example 3: Security Issues with gets() (β οΈ Demonstrating Dangerous Operation)
The following example shows why `gets()` is unsafe.
## Example
#include
int main()
{
// Warning: This example is dangerous, for demonstration only!
char buffer;
printf("Please enter a long string (more than 10 characters):n");
gets(buffer);// No boundary check, may cause buffer overflow
printf("You entered: %sn", buffer);
return(0);
}
**Code Analysis:**
* `buffer` only allocates 10 bytes of space.
* If the user inputs a string longer than 9 characters (plus the terminating ``), a **buffer overflow** occurs, potentially overwriting adjacent memory regions.
* This can be exploited by attackers to execute malicious code, hence `gets()` was marked as obsolete in C99 and removed entirely in C11.
### Better Alternative: fgets()
It's strongly recommended to use `fgets()` instead of `gets()` as it allows specifying buffer size.
## Example
#include
int main()
{
char str;
printf("Please enter a string: ");
// fgets(buffer, buffer_size, file_stream)
fgets(str,sizeof(str), stdin);
// Remove the newline character read by fgets
// Method: Find newline and replace with null character
for(int i =0; str!=''; i++){
if(str=='n'){
str='';
break;
}
}
printf("The string you entered is: %sn", str);
return(0);
}
**Advantages of `fgets()`:**
* Can specify maximum characters to read, preventing buffer overflow.
* Preserves newline character in the string (can be manually removed if needed).
* Can specify input source (standard input, file, etc.).
* * C Standard Library - ](#)
YouTip