1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 *
4 * HDF is dual licensed: you can use it either under the terms of
5 * the GPL, or the BSD license, at your option.
6 * See the LICENSE file in the root of this repository for complete details.
7 */
8
9 #include "file.h"
10 #include <climits>
11 #include <cstdlib>
12 #include "types.h"
13
14 using namespace OHOS::Hardware::Util;
15
AbsPath(const std::string & path)16 std::string File::AbsPath(const std::string &path)
17 {
18 char realPath[PATH_MAX];
19 #ifdef MINGW32
20 char *p = _fullpath(realPath, path.data(), PATH_MAX);
21 if (p != nullptr && access(p, F_OK) != 0) {
22 p = nullptr;
23 }
24 #else
25 char *p = realpath(path.data(), realPath);
26 #endif
27 return p == nullptr ? "" : p;
28 }
29
StripSuffix(std::string path)30 std::string File::StripSuffix(std::string path)
31 {
32 auto sepPos = path.rfind(OS_SEPARATOR);
33 auto dotPos = path.rfind('.');
34 if (sepPos == std::string::npos || dotPos > sepPos) {
35 return path.substr(0, dotPos);
36 } else {
37 return path;
38 }
39 }
40
GetDir(std::string path)41 std::string File::GetDir(std::string path)
42 {
43 auto separatorPos = path.rfind(OS_SEPARATOR);
44 if (separatorPos == std::string::npos) {
45 return path;
46 }
47 return path.substr(0, separatorPos + 1);
48 }
49
FileNameBase(const std::string & path)50 std::string File::FileNameBase(const std::string &path)
51 {
52 auto sepPos = path.rfind(OS_SEPARATOR);
53 auto dotPos = path.rfind('.');
54
55 if (sepPos == std::string::npos) {
56 sepPos = 0;
57 } else {
58 sepPos++;
59 }
60
61 if (dotPos == std::string::npos || dotPos < sepPos) {
62 dotPos = path.size();
63 }
64
65 auto len = path.size() - 1;
66 if (dotPos != std::string::npos && dotPos > sepPos) {
67 len = dotPos - sepPos;
68 }
69 return path.substr(sepPos, len);
70 }
71