2 * Copyright (c) 2011 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_utils.cpp
18 * @author Bartosz Janiak (b.janiak@samsung.com)
30 #include <dpl/exception.h>
31 #include <dpl/errno_string.h>
32 #include <file_utils.h>
34 #include <dpl/wrt-dao-ro/path_builder.h>
37 int try_mkdir(const char* path,
43 if (::stat(path, &st) != 0) {
44 if (::mkdir(path, mode) != 0) {
47 } else if (!S_ISDIR(st.st_mode)) {
55 int mkpath(const char* path,
58 char* copy = ::strdup(path);
67 while ((0 == err) && (NULL != (slash = ::strchr(ptr, '/')))) {
70 err = try_mkdir(copy, mode);
77 err = try_mkdir(path, mode);
84 int RmNode(const char* path);
86 int RmDir(const char* path)
88 DIR* dir = ::opendir(path);
93 struct dirent* entry = NULL;
96 if (NULL != (entry = ::readdir(dir))) {
97 if (!::strncmp(entry->d_name, ".", 1) ||
98 !::strncmp(entry->d_name, "..", 2)) {
101 std::string fullPath = WrtDB::PathBuilder(path)
102 .Append(entry->d_name)
104 if (RmNode(fullPath.c_str()) != 0) {
106 TEMP_FAILURE_RETRY(::closedir(dir));
112 while (NULL != entry);
115 if (TEMP_FAILURE_RETRY(::closedir(dir)) != 0) {
120 return (errno == 0 ? ::rmdir(path) : -1);
123 int RmNode(const char* path)
126 if (::lstat(path, &st) != 0) {
129 return (S_ISDIR(st.st_mode) ? RmDir(path) : ::unlink(path));
133 namespace FileUtils {
134 bool FileExists(const DPL::String& absolutePath)
136 struct stat statStruct;
137 if (stat(DPL::ToUTF8String(absolutePath).c_str(), &statStruct) == 0) {
138 return S_ISREG(statStruct.st_mode);
144 void MakePath(const std::string& path,
147 if (mkpath(path.c_str(), mode) == -1) {
148 ThrowMsg(DPL::CommonException::InternalError, "Cannot make path");
152 void RemoveDir(const std::string& path)
154 if (RmDir(path.c_str()) != 0) {
155 ThrowMsg(RemoveDirectoryException, DPL::GetErrnoString());