ae6dce2895d4b5319184bc8f8134eee2f8e3b88a
[scilab.git] / scilab / modules / fileio / src / cpp / fullpath.cpp
1 /*
2 * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3 * Copyright (C) 2019-2011 - St├ęphane MOTTELET
4 *
5  *
6  * This file is hereby licensed under the terms of the GNU GPL v2.0,
7  * pursuant to article 5.3.4 of the CeCILL v.2.1.
8  * This file was originally licensed under the terms of the CeCILL v2.1,
9  * and continues to be available under such terms.
10  * For more information, see the COPYING file which you should have received
11  * along with this program.
12 *
13 */
14 /*--------------------------------------------------------------------------*/
15
16 #include <filesystem>
17
18 extern "C"
19 {
20 #include "charEncoding.h"
21 #include "fullpath.h"
22 #include "sci_malloc.h"
23 #include "os_string.h"
24 }
25
26 char *get_full_path(const char *_Path)
27 {
28 #ifdef _MSC_VER
29     char *_FullPath = NULL;
30     wchar_t *wFullPath = NULL;
31     wchar_t *wPath = to_wide_string((char *)_Path);
32
33     if (wPath)
34     {
35         wFullPath = get_full_pathW(wPath);
36         FREE(wPath);
37         if (wFullPath)
38         {
39             _FullPath = wide_string_to_UTF8(wFullPath);
40             FREE(wFullPath);
41         }
42     }
43     return _FullPath;
44 #else // POSIX
45     std::filesystem::path relPath = std::filesystem::path(_Path);
46     std::filesystem::path canonPath = std::filesystem::weakly_canonical(relPath);
47     auto relPathIt = relPath.end();
48     auto canonPathIt = canonPath.end();
49     if ((--relPathIt)->string().empty() && !(--canonPathIt)->string().empty())
50     {
51         canonPath /= "";
52     }
53     return os_strdup(std::filesystem::absolute(canonPath).string().c_str());
54 #endif // _MSC_VER
55 }
56
57 /*--------------------------------------------------------------------------*/
58 wchar_t *get_full_pathW(const wchar_t * _wcPath)
59 {
60 #ifdef _MSC_VER
61     std::filesystem::path relPath = std::filesystem::path(_wcPath);
62     std::filesystem::path canonPath = std::filesystem::weakly_canonical(relPath);
63     auto relPathIt = relPath.end();
64     auto canonPathIt = canonPath.end();
65     if ((--relPathIt)->wstring().empty() && !(--canonPathIt)->wstring().empty())
66     {
67         canonPath /= "";
68     }
69     return os_wcsdup(std::filesystem::absolute(canonPath).wstring().c_str());
70 #else // POSIX
71     char *_FullPath = NULL;
72     wchar_t *wFullPath = NULL;
73     char *_Path = wide_string_to_UTF8(_wcPath);
74
75     if (_Path)
76     {
77         _FullPath = get_full_path(_Path);
78         FREE(_Path);
79         if (_FullPath)
80         {
81             wFullPath = to_wide_string(_FullPath);
82             FREE(_FullPath);
83         }
84     }
85     return wFullPath;
86 #endif // _MSC_VER
87 }
88
89