• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) Huawei Technologies Co., Ltd. 2014-2020. All rights reserved.
3  * Licensed under Mulan PSL v2.
4  * You can use this software according to the terms and conditions of the Mulan PSL v2.
5  * You may obtain a copy of Mulan PSL v2 at:
6  *          http://license.coscl.org.cn/MulanPSL2
7  * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
8  * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
9  * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
10  * See the Mulan PSL v2 for more details.
11  * Description: gets_s function
12  * Author: lishunda
13  * Create: 2014-02-25
14  */
15 
16 #include "securecutil.h"
17 
18 /*
19  * The parameter size is buffer size in byte
20  */
SecTrimCRLF(char * buffer,size_t size)21 SECUREC_INLINE void SecTrimCRLF(char *buffer, size_t size)
22 {
23     size_t len = strlen(buffer);
24     --len; /* Unsigned integer wrapping is accepted and is checked afterwards */
25     while (len < size && (buffer[len] == '\r' || buffer[len] == '\n')) {
26         buffer[len] = '\0';
27         --len; /* Unsigned integer wrapping is accepted and is checked next loop */
28     }
29 }
30 
31 /*
32  * <FUNCTION DESCRIPTION>
33  *    The gets_s function reads at most one less than the number of characters
34  *    specified by destMax from the std input stream, into the array pointed to by buffer
35  *    The line consists of all characters up to and including
36  *    the first newline character ('\n'). gets_s then replaces the newline
37  *    character with a null character ('\0') before returning the line.
38  *    If the first character read is the end-of-file character, a null character
39  *    is stored at the beginning of buffer and NULL is returned.
40  *
41  * <INPUT PARAMETERS>
42  *    buffer                         Storage location for input string.
43  *    destMax                        The size of the buffer.
44  *
45  * <OUTPUT PARAMETERS>
46  *    buffer                         is updated
47  *
48  * <RETURN VALUE>
49  *    buffer                         Successful operation
50  *    NULL                           Improper parameter or read fail
51  */
gets_s(char * buffer,size_t destMax)52 char *gets_s(char *buffer, size_t destMax)
53 {
54 #ifdef SECUREC_COMPATIBLE_WIN_FORMAT
55     size_t bufferSize = ((destMax == (size_t)(-1)) ? SECUREC_STRING_MAX_LEN : destMax);
56 #else
57     size_t bufferSize = destMax;
58 #endif
59 
60     if (buffer == NULL || bufferSize == 0 || bufferSize > SECUREC_STRING_MAX_LEN) {
61         SECUREC_ERROR_INVALID_PARAMTER("gets_s");
62         return NULL;
63     }
64 
65     if (fgets(buffer, (int)bufferSize, SECUREC_STREAM_STDIN) != NULL) {
66         SecTrimCRLF(buffer, bufferSize);
67         return buffer;
68     }
69 
70     return NULL;
71 }
72 
73