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>
119 template<typename Postfix, typename... Rest>
120 struct Pre<Postfix, Rest...>
122 static const double value;
123 static std::string printSize(double fileSize)
125 if(fileSize >= Pre<Rest...>::value) {
126 double now = fileSize / Pre<Rest...>::value;
127 std::ostringstream outputStream;
128 outputStream.setf(std::ios::fixed, std::ios::floatfield);
129 outputStream.precision(2);
130 outputStream << now << Postfix::get();
131 return outputStream.str();
133 return Pre<Rest...>::printSize(fileSize);
142 static const double value;
143 static std::string printSize(double /*fileSize*/)
150 const double Pre<>::value = 1.0;
151 template<typename Postfix, typename... Params> const double Pre<Postfix, Params...>::value(Pre<>::value * stepSize);
154 typedef Pre<PrefixGB, PrefixMB, PrefixKB, PrefixB> FolderSizeToStringType;
157 } //anonymous namespace
160 DPL::String fromFileSizeString(size_t fileSize)
164 FolderSizeToStringType::printSize(static_cast<double>(fileSize));
165 return DPL::FromUTF8String(output);
168 } // end of namespace Utils