- 1. 关键词
- 2. fileutil.h
- 3. fileutil.cpp
- 4. filesystem_win.h
- 5. filesystem_win.cpp
- 6. filesystem_unix.cpp
- 7. 源码地址
1. 关键词
C++ 文件系统操作 获取文件的大小 获取文件夹的大小 跨平台
2. fileutil.h
#pragma once
#include <string>
#include <cstdio>
#include <cstdint>
#include "filetype.h"
#include "filepath.h"
namespace cutl
{
/**
* @brief The file guard class to manage the FILE pointer automatically.
* file_guard object can close the FILE pointer automatically when his scope is exit.
*/
class file_guard
{
public:
/**
* @brief Construct a new file guard object
*
* @param file the pointer of the FILE object
*/
explicit file_guard(FILE *file);
/**
* @brief Destroy the file guard object
*
*/
~file_guard();
/**
* @brief Get the FILE pointer.
*
* @return FILE*
*/
FILE *getfd() const;
private:
FILE *file_;
};
/**
* @brief Get the size of a file.
*
* @param filepath the filepath of the file to be checked
*
* @param link_target whether to get the size of the file pointed by symbolic link, default is false.
* If link_target is true, the function will get the size of the file pointed by symbolic link, not the symbolic link itself.
*
* @note link_target parameter only works on Unix-like systems, not support on Windows.
*
* @return file size in bytes
*/
uint64_t filesize(const filepath &filepath, bool link_target = false);
/**
* @brief Get the size of a directory, include all files and subdirectories.
*
* @param dirpath the filepath of the directory to be checked
* @return the total size of the directory in bytes
*/
uint64_t dirsize(const filepath &dirpath);
} // namespace cutl
3. fileutil.cpp
#include <cstdio>
#include <map>
#include <iostream>
#include <cstring>
#include <sys/stat.h>
#include "fileutil.h"
#include "inner/logger.h"
#include "inner/filesystem.h"
#include "strutil.h"
namespace cutl
{
file_guard::file_guard(FILE *file)
: file_(file)
{
}
file_guard::~file_guard()
{
if (file_)
{
// CUTL_DEBUG("close file");
int ret = fclose(file_);
if (ret != 0)
{
CUTL_ERROR("fail to close file, ret" + std::to_string(ret));
}
file_ = nullptr;
}
// ROBOLOG_DCHECK(file_ == nullptr);
}
FILE *file_guard::getfd() const
{
return file_;
}
uint64_t filesize(const filepath &filepath, bool link_target)
{
if (!filepath.exists())
{
CUTL_ERROR("filepath does not exist: " + filepath.str());
return 0;
}
return get_filesize(filepath.str(), link_target);
}
uint64_t dirsize(const filepath &dirpath)
{
return get_dirsize(dirpath.str());
}
4. filesystem_win.h
#include <vector>
#include <string>
#pragma once
namespace cutl
{
// get file size in bytes
uint64_t get_filesize(const std::string &filepath, bool link_target);
// get directory size in bytes
uint64_t get_dirsize(const std::string &dirpath);
} // namespace cutl
5. filesystem_win.cpp
#if defined(_WIN32) || defined(__WIN32__)
#include <io.h>
#include <direct.h>
#include <Windows.h>
#include <stdlib.h>
#include "strutil.h"
#include "filesystem.h"
#include "logger.h"
namespace cutl
{
// get file size in bytes
uint64_t get_filesize(const std::string &filepath, bool link_target)
{
struct stat statbuf;
int ret = stat(filepath.c_str(), &statbuf);
if (ret != 0)
{
CUTL_ERROR("stat " + filepath + " error, ret:" + std::to_string(ret));
return 0;
}
return static_cast<uint64_t>(statbuf.st_size);
}
// get directory size in bytes
uint64_t get_dirsize(const std::string &dirpath)
{
uint64_t totalSize = 0;
auto findpath = dirpath + win_separator + "*.*";
WIN32_FIND_DATAA data = {0};
HANDLE hFind = FindFirstFileA(findpath.c_str(), &data);
bool unicode = true;
if (hFind == INVALID_HANDLE_VALUE || hFind == NULL)
{
CUTL_ERROR("FindFirstFileA failed for " + findpath + ", errCode: " + std::to_string(GetLastError()));
return totalSize;
}
do
{
auto dwAttrs = data.dwFileAttributes;
auto filename = std::string(data.cFileName);
if (is_special_dir(filename))
{
// “..”和“.”不做处理
continue;
}
std::string filepath = dirpath + win_separator + filename;
if ((dwAttrs & FILE_ATTRIBUTE_DIRECTORY))
{
// directory
auto subdir_size = get_dirsize(filepath);
totalSize += subdir_size;
}
else
{
// file
auto subfile_size = get_filesize(filepath, false);
totalSize += subfile_size;
}
} while (FindNextFileA(hFind, &data));
// 关闭句柄
FindClose(hFind);
return totalSize;
}
} // namespace cutl
#endif // defined(_WIN32) || defined(__WIN32__)
6. filesystem_unix.cpp
#if defined(_WIN32) || defined(__WIN32__)
// do nothing
#else
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stack>
#include <cstring>
#include <utime.h>
#include <stdlib.h>
#include <sys/time.h>
#include "filesystem.h"
#include "inner/logger.h"
namespace cutl
{
uint64_t get_filesize(const std::string &filepath, bool link_target)
{
struct stat statbuf;
int ret = 0;
if (link_target)
{
ret = stat(filepath.c_str(), &statbuf);
}
else
{
ret = lstat(filepath.c_str(), &statbuf);
}
if (ret != 0)
{
CUTL_ERROR("stat " + filepath + " error, ret:" + std::to_string(ret));
return 0;
}
return static_cast<uint64_t>(statbuf.st_size);
}
filetype get_file_type(int mode)
{
filetype type = filetype::unknown;
if (S_ISBLK(mode))
{
type = filetype::block_special;
}
else if (S_ISCHR(mode))
{
type = filetype::char_special;
}
else if (S_ISDIR(mode))
{
type = filetype::directory;
}
else if (S_ISFIFO(mode))
{
type = filetype::pipefifo;
}
else if (S_ISLNK(mode))
{
type = filetype::symlink;
}
else if (S_ISREG(mode))
{
type = filetype::file;
}
else if (S_ISSOCK(mode))
{
type = filetype::socket;
}
return type;
}
uint64_t get_dirsize(const std::string &dirpath)
{
uint64_t totalSize = 0;
// filevec file_list;
DIR *dir = opendir(dirpath.c_str()); // 打开这个目录
if (dir == NULL)
{
CUTL_ERROR("opendir error. dirpath:" + dirpath + ", error:" + strerror(errno));
return totalSize;
}
struct dirent *file_info = NULL;
// 逐个读取目录中的文件到file_info
while ((file_info = readdir(dir)) != NULL)
{
// 系统有个系统文件,名为“..”和“.”,对它不做处理
std::string filename(file_info->d_name);
if (is_special_dir(filename))
{
continue;
}
struct stat file_stat; // 文件的信息
std::string filepath = dirpath + unix_separator + filename;
int ret = lstat(filepath.c_str(), &file_stat);
if (0 != ret)
{
CUTL_ERROR("stat error. filepath:" + filepath + ", error:" + strerror(errno));
closedir(dir);
return totalSize;
}
auto ftype = get_file_type(file_stat.st_mode);
if (S_ISDIR(file_stat.st_mode))
{
auto subdir_size = get_dirsize(filepath);
totalSize += subdir_size;
}
else
{
auto subfile_size = get_filesize(filepath, false);
totalSize += subfile_size;
}
}
closedir(dir);
return totalSize;
}
} // namespace cutl
#endif // defined(_WIN32) || defined(__WIN32__)
7. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。
【SunLogging】
扫码二维码,关注微信公众号,阅读更多精彩内容