1 /*
2 * Copyright (c) 2022-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 "b_filesystem/b_file.h"
17
18 #include <sys/sendfile.h>
19
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 #include <unique_fd.h>
23
24 namespace OHOS::FileManagement::Backup {
25 using namespace std;
26
ReadFile(const UniqueFd & fd)27 unique_ptr<char[]> BFile::ReadFile(const UniqueFd &fd)
28 {
29 if (lseek(fd, 0, SEEK_SET) == -1) {
30 GTEST_LOG_(INFO) << "BFile::ReadFile lseek error " << errno;
31 return make_unique<char[]>(1);
32 }
33
34 struct stat stat = {};
35 if (fstat(fd, &stat) == -1) {
36 GTEST_LOG_(INFO) << "BFile::ReadFile fstat error " << errno;
37 return make_unique<char[]>(1);
38 }
39 off_t fileSize = stat.st_size;
40 if (fileSize == 0) {
41 GTEST_LOG_(INFO) << "BFile::ReadFile fileSize error " << fileSize;
42 return make_unique<char[]>(1);
43 }
44
45 auto buf = make_unique<char[]>(fileSize + 1);
46 if (read(fd, buf.get(), fileSize) == -1) {
47 GTEST_LOG_(INFO) << "BFile::ReadFile read error " << errno;
48 }
49 return buf;
50 }
51
SendFile(int outFd,int inFd)52 void BFile::SendFile(int outFd, int inFd)
53 {
54 if (outFd <= 0 || inFd <= 0) {
55 return;
56 }
57 off_t offset = 0;
58 long ret = 0;
59 if (lseek(outFd, 0, SEEK_SET) == -1) {
60 GTEST_LOG_(INFO) << "BFile::SendFile lseek1 error " << errno;
61 return;
62 }
63 if (lseek(inFd, 0, SEEK_SET) == -1) {
64 GTEST_LOG_(INFO) << "BFile::SendFile lseek2 error " << errno;
65 return;
66 }
67 struct stat stat = {};
68 if (fstat(inFd, &stat) == -1) {
69 GTEST_LOG_(INFO) << "BFile::SendFile fstat error " << errno;
70 return;
71 }
72 while ((ret = sendfile(outFd, inFd, &offset, stat.st_size)) > 0) {
73 };
74
75 if (ret == -1) {
76 GTEST_LOG_(INFO) << "BFile::SendFile ret error " << ret;
77 }
78 }
79
Write(const UniqueFd & fd,const string & str)80 void BFile::Write(const UniqueFd &fd, const string &str) {}
81
CopyFile(const string & from,const string & to)82 bool BFile::CopyFile(const string &from, const string &to)
83 {
84 return true;
85 }
86
MoveFile(const string & from,const string & to)87 bool BFile::MoveFile(const string &from, const string &to)
88 {
89 return true;
90 }
91 } // namespace OHOS::FileManagement::Backup