• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 "file_utils.h"
17 
18 #include <sys/types.h>
19 #include <unistd.h>
20 
21 #include "dfs_error.h"
22 #include "utils_log.h"
23 
24 namespace OHOS {
25 namespace FileManagement {
ReadFile(int fd,off_t offset,size_t size,void * data)26 int64_t FileUtils::ReadFile(int fd, off_t offset, size_t size, void *data)
27 {
28     if ((fd < 0) || (offset < 0) || (size < 0) || (data == nullptr)) {
29         LOGE("invalid params, fd %{public}d, offset %{public}d, size %{public}zu, or buf is null", fd,
30              static_cast<int>(offset), size);
31         return -1;
32     }
33 
34     off_t err = lseek(fd, offset, SEEK_SET);
35     if (err < 0) {
36         return -errno;
37     }
38 
39     size_t readLen = 0;
40     while (readLen < size) {
41         ssize_t ret = read(fd, data, size - readLen);
42         if (ret < 0) {
43             LOGE("read failed, errno %{public}d, fd=%{public}d", errno, fd);
44             return ret;
45         } else if (ret == 0) {
46             break;
47         }
48         readLen += ret;
49     }
50 
51     return readLen;
52 }
53 
WriteFile(int fd,const void * data,off_t offset,size_t size)54 int64_t FileUtils::WriteFile(int fd, const void *data, off_t offset, size_t size)
55 {
56     if ((fd < 0) || (offset < 0) || (size < 0) || (data == nullptr)) {
57         LOGE("invalid params, fd %{public}d, offset %{public}d, size %{public}zu, or buf is null", fd,
58              static_cast<int>(offset), size);
59         return -1;
60     }
61 
62     off_t err = lseek(fd, offset, SEEK_SET);
63     if (err < 0) {
64         return -errno;
65     }
66 
67     size_t writeLen = 0;
68     while (writeLen < size) {
69         ssize_t ret = write(fd, data, size - writeLen);
70         if (ret <= 0) {
71             LOGE("write failed, errno %{public}d, fd=%{public}d", errno, fd);
72             return ret;
73         }
74         writeLen += ret;
75     }
76 
77     return writeLen;
78 }
79 } // namespace FileManagement
80 } // namespace OHOS
81