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>
37 size_t getFolderSize(const std::string& path)
42 char * const paths[] = { const_cast<char * const>(path.c_str()), NULL };
44 if ((fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) {
47 LogWarning(__PRETTY_FUNCTION__ << ": fts_open failed with error: "
52 while ((ftsent = fts_read(fts)) != NULL) {
53 switch (ftsent->fts_info) {
56 //directory in postorder and directory causing a loop
64 //regular files and other objects that can be counted
65 size += ftsent->fts_statp->st_size;
72 LogWarning(__PRETTY_FUNCTION__
73 << ": traversal failed on file: "
76 << strerror(ftsent->fts_errno));
81 if (fts_close(fts) == -1) {
83 LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: "
92 #define DECLARE_PREFIX_STRUCT(name) \
95 static std::string get() \
97 return std::string(#name); \
101 DECLARE_PREFIX_STRUCT(B)
102 DECLARE_PREFIX_STRUCT(KB)
103 DECLARE_PREFIX_STRUCT(MB)
104 DECLARE_PREFIX_STRUCT(GB)
106 #undef DECLARE_PREFIX_STRUCT
108 const int stepSize = 1024;
109 template<typename ... Rest>
112 template<typename Postfix, typename ... Rest>
113 struct Pre<Postfix, Rest ...>
115 static const double value;
116 static std::string printSize(double fileSize)
118 if (fileSize >= Pre<Rest ...>::value) {
119 double now = fileSize / Pre<Rest ...>::value;
120 std::ostringstream outputStream;
121 outputStream.setf(std::ios::fixed, std::ios::floatfield);
122 outputStream.precision(2);
123 outputStream << now << Postfix::get();
124 return outputStream.str();
126 return Pre<Rest ...>::printSize(fileSize);
134 static const double value;
135 static std::string printSize(double /*fileSize*/)
141 const double Pre<>::value = 1.0;
142 template<typename Postfix, typename ... Params> const double Pre<Postfix,
144 value(Pre<>::value * stepSize);
146 typedef Pre<PrefixGB, PrefixMB, PrefixKB, PrefixB> FolderSizeToStringType;
147 } //anonymous namespace
149 DPL::String fromFileSizeString(size_t fileSize)
152 FolderSizeToStringType::printSize(static_cast<double>(fileSize));
153 return DPL::FromUTF8String(output);
155 } // end of namespace Utils