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.
18 * @file folder_size.cpp
19 * @author Jaroslaw Osmanski (j.osmanski@samsung.com)
21 * @brief Implementation for function calculating directory size
25 #include <sys/types.h>
32 #include <dpl/log/log.h>
33 #include <dpl/foreach.h>
34 #include <dpl/utils/folder_size.h>
38 size_t getFolderSize(const std::string& path)
43 char * const paths[] = {const_cast<char * const>(path.c_str()), NULL};
45 if ((fts = fts_open(paths, FTS_PHYSICAL|FTS_NOCHDIR, NULL)) == NULL) {
48 LogWarning(__PRETTY_FUNCTION__ << ": fts_open failed with error: "
53 while ((ftsent = fts_read(fts)) != NULL) {
54 switch (ftsent->fts_info) {
57 //directory in postorder and directory causing a loop
65 //regular files and other objects that can be counted
66 size += ftsent->fts_statp->st_size;
73 LogWarning(__PRETTY_FUNCTION__
74 << ": traversal failed on file: "
77 << strerror(ftsent->fts_errno));
82 if (fts_close(fts) == -1) {
84 LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: "
97 #define DECLARE_PREFIX_STRUCT(name) \
100 static std::string get() \
102 return std::string(#name); \
106 DECLARE_PREFIX_STRUCT(B)
107 DECLARE_PREFIX_STRUCT(KB)
108 DECLARE_PREFIX_STRUCT(MB)
109 DECLARE_PREFIX_STRUCT(GB)
111 #undef DECLARE_PREFIX_STRUCT
114 const int stepSize = 1024;
115 template<typename... Rest>
118 template<typename Postfix, typename... Rest>
119 struct Pre<Postfix, Rest...>
121 static const double value = Pre<Rest...>::value * stepSize;
122 static std::string printSize(double fileSize)
124 if(fileSize >= Pre<Rest...>::value) {
125 double now = fileSize / Pre<Rest...>::value;
126 std::ostringstream outputStream;
127 outputStream.setf(std::ios::fixed, std::ios::floatfield);
128 outputStream.precision(2);
129 outputStream << now << Postfix::get();
130 return outputStream.str();
132 return Pre<Rest...>::printSize(fileSize);
141 static const double value;
142 static std::string printSize(double /*fileSize*/)
148 const double Pre<>::value = 1.0;
150 typedef Pre<PrefixGB, PrefixMB, PrefixKB, PrefixB> FolderSizeToStringType;
151 } //anonymous namespace
154 DPL::String fromFileSizeString(size_t fileSize)
158 FolderSizeToStringType::printSize(static_cast<double>(fileSize));
159 return DPL::FromUTF8String(output);
162 } // end of namespace Utils