1 /*
2 * Copyright (c) 2021 Bestechnic (Shanghai) Co., Ltd. All rights reserved.
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 #define _GNU_SOURCE
16 #include <string.h>
17 #include "utils_file.h"
18 #define LOG_TAG "UtilsFile"
19 #include "log.h"
20
21 #define UtilsFileAssert(cond, expr) \
22 do { \
23 if (!(cond)) { \
24 HILOG_ERROR(HILOG_MODULE_APP, "%d: '%s' failed", __LINE__, #cond); \
25 expr; \
26 } \
27 } while (0)
28
utils_file_test(void)29 void utils_file_test(void)
30 {
31 const char *path = "/data/test.txt";
32 const char *data = "utils_file_test";
33 const int whence[3] = {SEEK_SET_FS, SEEK_CUR_FS, SEEK_END_FS};
34 char buf[64] = {0};
35 unsigned int fileSize = 0;
36
37 int ret;
38 int fd = UtilsFileOpen(path, O_WRONLY_FS | O_CREAT_FS, 0664);
39 UtilsFileAssert(fd >= 0, return );
40
41 ret = UtilsFileWrite(fd, data, strlen(data));
42 UtilsFileAssert(ret == strlen(data), goto ERR);
43 ret = UtilsFileClose(fd);
44 UtilsFileAssert(ret == 0, return );
45
46 fd = UtilsFileOpen(path, O_RDONLY_FS, 0);
47 UtilsFileAssert(fd >= 0, return );
48 ret = UtilsFileStat(path, &fileSize);
49 UtilsFileAssert(ret == 0, goto ERR);
50 HILOG_DEBUG(HILOG_MODULE_APP, "fileSize %u", fileSize);
51
52 for (int i = 0; i < 3; i++) {
53 ret = UtilsFileSeek(fd, 0, whence[i]);
54 UtilsFileAssert(ret >= 0, goto ERR);
55 }
56
57 UtilsFileSeek(fd, 0, SEEK_SET_FS);
58 ret = UtilsFileRead(fd, buf, 4);
59 UtilsFileAssert(ret == 4, goto ERR);
60 buf[4] = '\0';
61 HILOG_DEBUG(HILOG_MODULE_APP, "read: %s", buf);
62 UtilsFileSeek(fd, 2, SEEK_SET_FS);
63 ret = UtilsFileRead(fd, buf, 4);
64 UtilsFileAssert(ret == 4, goto ERR);
65 buf[4] = '\0';
66 HILOG_DEBUG(HILOG_MODULE_APP, "read: %s", buf);
67
68 ERR:
69 ret = UtilsFileClose(fd);
70 UtilsFileAssert(ret == 0, return );
71 ret = UtilsFileDelete(path);
72 UtilsFileAssert(ret == 0, return );
73 }
74