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)
29 #include <dpl/exception.h>
30 #include <dpl/errno_string.h>
31 #include <dpl/utils/file_utils.h>
33 #include <dpl/wrt-dao-ro/path_builder.h>
36 int try_mkdir(const char* path,
42 if (::stat(path, &st) != 0) {
43 if (::mkdir(path, mode) != 0) {
46 } else if (!S_ISDIR(st.st_mode)) {
54 int mkpath(const char* path,
57 char* copy = ::strdup(path);
66 while ((0 == err) && (NULL != (slash = ::strchr(ptr, '/')))) {
69 err = try_mkdir(copy, mode);
76 err = try_mkdir(path, mode);
83 int RmNode(const char* path);
85 int RmDir(const char* path)
87 DIR* dir = ::opendir(path);
92 struct dirent* entry = NULL;
95 if (NULL != (entry = ::readdir(dir))) {
96 if (!::strncmp(entry->d_name, ".", 1) ||
97 !::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));
111 } while (NULL != entry);
114 if (TEMP_FAILURE_RETRY(::closedir(dir)) != 0) {
119 return (errno == 0 ? ::rmdir(path) : -1);
122 int RmNode(const char* path)
125 if (::lstat(path, &st) != 0) {
128 return (S_ISDIR(st.st_mode) ? RmDir(path) : ::unlink(path));
132 namespace FileUtils {
133 bool FileExists(const DPL::String& absolutePath)
135 struct stat statStruct;
136 if (stat(DPL::ToUTF8String(absolutePath).c_str(), &statStruct) == 0) {
137 return S_ISREG(statStruct.st_mode);
143 void MakePath(const std::string& path,
146 if (mkpath(path.c_str(), mode) == -1) {
147 ThrowMsg(CreateDirectoryException, "Cannot make path");
151 void RemoveDir(const std::string& path)
153 if (RmDir(path.c_str()) != 0) {
154 ThrowMsg(RemoveDirectoryException, DPL::GetErrnoString());