• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 #ifndef PREFERENCES_FILE_OPERATION_H
16 #define PREFERENCES_FILE_OPERATION_H
17 
18 #include <fcntl.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 
22 #include <string>
23 
24 #include "visibility.h"
25 
26 #if defined(WINDOWS_PLATFORM)
27 
28 #include <iostream>
29 #include <windows.h>
30 
31 #else
32 
33 #include <stdarg.h>
34 
35 #if !(defined(MAC_PLATFORM) || defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM))
36 
37 #include <cstdlib>
38 
39 #endif
40 
41 #endif
42 
43 #ifndef FILE_MODE
44 #define FILE_MODE 0770
45 #endif
46 
47 #ifndef FILE_EXIST
48 #define FILE_EXIST 0
49 #endif
50 
51 #ifndef INT_MAX
52 #define INT_MAX 2147483647
53 #endif
54 
55 namespace OHOS {
56 namespace NativePreferences {
Mkdir(const std::string & filePath)57 static UNUSED_FUNCTION int Mkdir(const std::string &filePath)
58 {
59 #if defined(WINDOWS_PLATFORM)
60     return mkdir(filePath.c_str());
61 #else
62     return mkdir(filePath.c_str(), FILE_MODE);
63 #endif
64 }
65 
Access(const std::string & filePath)66 static UNUSED_FUNCTION int Access(const std::string &filePath)
67 {
68 #if defined(WINDOWS_PLATFORM)
69     return _access(filePath.c_str(), FILE_EXIST);
70 #else
71     return access(filePath.c_str(), FILE_EXIST);
72 #endif
73 }
74 
Fsync(const std::string & filePath)75 static UNUSED_FUNCTION bool Fsync(const std::string &filePath)
76 {
77 #if defined(WINDOWS_PLATFORM)
78     int fd = _open(filePath.c_str(), _O_WRONLY, _S_IWRITE);
79     if (fd == -1) {
80         return false;
81     }
82     HANDLE handle = (HANDLE)_get_osfhandle(fd);
83     if (handle == INVALID_HANDLE_VALUE || !FlushFileBuffers(handle)) {
84         _close(fd);
85         return false;
86     }
87     _close(fd);
88 #else
89     int fd = open(filePath.c_str(), O_RDWR, S_IRUSR | S_IWUSR);
90     if (fd == -1 || fsync(fd) == -1) {
91         close(fd);
92         return false;
93     }
94     close(fd);
95 #endif
96     return true;
97 }
98 } // namespace NativePreferences
99 } // namespace OHOS
100 #endif // PREFERENCES_FILE_OPERATION_H