2 * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
17 * @file file-system.cpp
18 * @author Sangwan Kwon (sangwan.kwon@samsung.com)
22 #include "file-system.hxx"
31 #include "exception.hxx"
35 void File::linkTo(const std::string &src, const std::string &dst)
37 if (::symlink(src.c_str(), dst.c_str()))
38 ThrowErrno(errno, "Failed to link " + src + " -> " + dst);
41 std::string File::read(const std::string &path)
43 FilePtr fp = FilePtr(::fopen(path.c_str(), "rb"), ::fclose);
45 throw std::invalid_argument("Failed to open [" + path + "].");
47 std::fseek(fp.get(), 0L, SEEK_END);
48 unsigned int fsize = std::ftell(fp.get());
49 std::rewind(fp.get());
51 std::string buff(fsize, 0);
52 if (fsize != std::fread(static_cast<void*>(&buff[0]), 1, fsize, fp.get()))
53 throw std::logic_error("Failed to read [" + path + "]");
57 std::string File::readLink(const std::string &path)
59 std::vector<char> buf(PATH_MAX);
60 ssize_t count = ::readlink(path.c_str(), buf.data(), buf.size());
61 return std::string(buf.data(), (count > 0) ? count : 0);
64 std::string File::getName(const std::string &path)
66 size_t pos = path.rfind('/');
67 if (pos == std::string::npos)
68 throw std::invalid_argument("Path is wrong. > " + path);
69 return path.substr(pos + 1);
72 } // namespace tanchor