1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "param_utils.h"
17
18 #include <ctype.h>
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <pwd.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <time.h>
27 #include <unistd.h>
28
29 #include "init_utils.h"
30
CheckAndCreateDir(const char * fileName)31 void CheckAndCreateDir(const char *fileName)
32 {
33 if (fileName == NULL || *fileName == '\0') {
34 return;
35 }
36 char *path = strndup(fileName, strrchr(fileName, '/') - fileName);
37 if (path == NULL) {
38 return;
39 }
40 if (access(path, F_OK) == 0) {
41 free(path);
42 return;
43 }
44 MakeDirRecursive(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
45 free(path);
46 }
47
TrimString(char * string,uint32_t currLen)48 static void TrimString(char *string, uint32_t currLen)
49 {
50 for (int i = currLen - 1; i >= 0; i--) {
51 if (string[i] == ' ' || string[i] == '\0') {
52 string[i] = '\0';
53 } else {
54 break;
55 }
56 }
57 }
58
GetSubStringInfo(const char * buff,uint32_t buffLen,char delimiter,SubStringInfo * info,int subStrNumber)59 int GetSubStringInfo(const char *buff, uint32_t buffLen, char delimiter, SubStringInfo *info, int subStrNumber)
60 {
61 PARAM_CHECK(buff != NULL && info != NULL, return 0, "Invalid buff");
62 size_t i = 0;
63 // 去掉开始的空格
64 for (; i < strlen(buff); i++) {
65 if (!isspace(buff[i])) {
66 break;
67 }
68 }
69 // 过滤掉注释
70 if (buff[i] == '#') {
71 return -1;
72 }
73 // 分割字符串
74 int spaceIsValid = 0;
75 int curr = 0;
76 int valueCurr = 0;
77 for (; i < buffLen; i++) {
78 if (buff[i] == '\n' || buff[i] == '\r' || buff[i] == '\0') {
79 break;
80 }
81 if (buff[i] == delimiter && valueCurr != 0) {
82 info[curr].value[valueCurr] = '\0';
83 TrimString(info[curr].value, valueCurr);
84 valueCurr = 0;
85 curr++;
86 spaceIsValid = 0;
87 } else {
88 if (!spaceIsValid && isspace(buff[i])) { // 过滤开始前的无效字符
89 continue;
90 }
91 spaceIsValid = 1;
92 if ((valueCurr + 1) >= (int)sizeof(info[curr].value)) {
93 continue;
94 }
95 info[curr].value[valueCurr++] = buff[i];
96 }
97 if (curr >= subStrNumber) {
98 break;
99 }
100 }
101 if (valueCurr > 0) {
102 info[curr].value[valueCurr] = '\0';
103 TrimString(info[curr].value, valueCurr);
104 valueCurr = 0;
105 curr++;
106 }
107 return curr;
108 }