You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

gets_s.c 2.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "securecutil.h"
  17. static void SecTrimCRLF(char *buffer, size_t len)
  18. {
  19. int i;
  20. /* No need to determine whether integer overflow exists */
  21. for (i = (int)(len - 1); i >= 0 && (buffer[i] == '\r' || buffer[i] == '\n'); --i) {
  22. buffer[i] = '\0';
  23. }
  24. return;
  25. }
  26. /*
  27. * <FUNCTION DESCRIPTION>
  28. * The gets_s function reads at most one less than the number of characters
  29. * specified by destMax from the stream pointed to by stdin, into the array pointed to by buffer
  30. * The line consists of all characters up to and including
  31. * the first newline character ('\n'). gets_s then replaces the newline
  32. * character with a null character ('\0') before returning the line.
  33. * If the first character read is the end-of-file character, a null character
  34. * is stored at the beginning of buffer and NULL is returned.
  35. *
  36. * <INPUT PARAMETERS>
  37. * buffer Storage location for input string.
  38. * numberOfElements The size of the buffer.
  39. *
  40. * <OUTPUT PARAMETERS>
  41. * buffer is updated
  42. *
  43. * <RETURN VALUE>
  44. * buffer Successful operation
  45. * NULL Improper parameter or read fail
  46. */
  47. char *gets_s(char *buffer, size_t numberOfElements)
  48. {
  49. size_t len;
  50. #ifdef SECUREC_COMPATIBLE_WIN_FORMAT
  51. size_t bufferSize = ((numberOfElements == (size_t)-1) ? SECUREC_STRING_MAX_LEN : numberOfElements);
  52. #else
  53. size_t bufferSize = numberOfElements;
  54. #endif
  55. if (buffer == NULL || bufferSize == 0 || bufferSize > SECUREC_STRING_MAX_LEN) {
  56. SECUREC_ERROR_INVALID_PARAMTER("gets_s");
  57. return NULL;
  58. }
  59. if (fgets(buffer, (int)bufferSize, stdin) == NULL) {
  60. return NULL;
  61. }
  62. len = strlen(buffer);
  63. if (len > 0 && len < bufferSize) {
  64. SecTrimCRLF(buffer, len);
  65. }
  66. return buffer;
  67. }