1 /*
2 * Copyright (c) 2025 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 "utimes_core.h"
17
18 #include <unistd.h>
19
20 #include "filemgmt_libhilog.h"
21 #include "fs_utils.h"
22
23 namespace OHOS {
24 namespace FileManagement {
25 namespace ModuleFileIO {
26 using namespace std;
27
DoUtimes(const string & path,const double mtime)28 FsResult<void> UtimesCore::DoUtimes(const string &path, const double mtime)
29 {
30 if (mtime < 0) {
31 HILOGE("Invalid mtime");
32 return FsResult<void>::Error(EINVAL);
33 }
34 std::unique_ptr<uv_fs_t, decltype(FsUtils::FsReqCleanup)*> statReq = {
35 new (std::nothrow) uv_fs_t, FsUtils::FsReqCleanup };
36 if (!statReq) {
37 HILOGE("Failed to request heap memory.");
38 return FsResult<void>::Error(ENOMEM);
39 }
40 int ret = uv_fs_stat(nullptr, statReq.get(), path.c_str(), nullptr);
41 if (ret < 0) {
42 HILOGE("Failed to get stat of the file by path");
43 return FsResult<void>::Error(ret);
44 }
45
46 std::unique_ptr<uv_fs_t, decltype(FsUtils::FsReqCleanup)*> utimesReq = {
47 new uv_fs_t, FsUtils::FsReqCleanup };
48 if (!utimesReq) {
49 HILOGE("Failed to request heap memory.");
50 return FsResult<void>::Error(ENOMEM);
51 }
52
53 double atime = static_cast<double>(statReq->statbuf.st_atim.tv_sec) +
54 static_cast<double>(statReq->statbuf.st_atim.tv_nsec) / NS;
55 ret = uv_fs_utime(nullptr, utimesReq.get(), path.c_str(), atime, mtime / MS, nullptr);
56 if (ret < 0) {
57 HILOGE("Failed to chang mtime of the file for %{public}d", ret);
58 return FsResult<void>::Error(ret);
59 }
60 return FsResult<void>::Success();
61 }
62 } // ModuleFileIO
63 } // FileManagement
64 } // OHOS