1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2014-2021. 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 * Create: 2014-02-25
13 */
14
15 #include "securecutil.h"
16
17 /*
18 * The parameter size is buffer size in byte
19 */
SecTrimCRLF(char * buffer,size_t size)20 SECUREC_INLINE void SecTrimCRLF(char *buffer, size_t size)
21 {
22 size_t len = strlen(buffer);
23 --len; /* Unsigned integer wrapping is accepted and is checked afterwards */
24 while (len < size && (buffer[len] == '\r' || buffer[len] == '\n')) {
25 buffer[len] = '\0';
26 --len; /* Unsigned integer wrapping is accepted and is checked next loop */
27 }
28 }
29
30 /*
31 * <FUNCTION DESCRIPTION>
32 * The gets_s function reads at most one less than the number of characters
33 * specified by destMax from the std input stream, into the array pointed to by buffer
34 * The line consists of all characters up to and including
35 * the first newline character ('\n'). gets_s then replaces the newline
36 * character with a null character ('\0') before returning the line.
37 * If the first character read is the end-of-file character, a null character
38 * is stored at the beginning of buffer and NULL is returned.
39 *
40 * <INPUT PARAMETERS>
41 * buffer Storage location for input string.
42 * destMax The size of the buffer.
43 *
44 * <OUTPUT PARAMETERS>
45 * buffer is updated
46 *
47 * <RETURN VALUE>
48 * buffer Successful operation
49 * NULL Improper parameter or read fail
50 */
gets_s(char * buffer,size_t destMax)51 char *gets_s(char *buffer, size_t destMax)
52 {
53 #ifdef SECUREC_COMPATIBLE_WIN_FORMAT
54 size_t bufferSize = ((destMax == (size_t)(-1)) ? SECUREC_STRING_MAX_LEN : destMax);
55 #else
56 size_t bufferSize = destMax;
57 #endif
58
59 if (buffer == NULL || bufferSize == 0 || bufferSize > SECUREC_STRING_MAX_LEN) {
60 SECUREC_ERROR_INVALID_PARAMTER("gets_s");
61 return NULL;
62 }
63
64 if (fgets(buffer, (int)bufferSize, SECUREC_STREAM_STDIN) != NULL) {
65 SecTrimCRLF(buffer, bufferSize);
66 return buffer;
67 }
68
69 return NULL;
70 }
71
72