【问题标题】:Checking files size from current directory从当前目录检查文件大小
【发布时间】:2014-10-19 11:31:55
【问题描述】:

下面的函数读取目录并将文件名(通过 push_back())插入向量中

#include <dirent.h>

void open(string path){

    DIR* dir;
    dirent *pdir;

    dir = opendir(path.c_str());
    while (pdir = readdir(dir)){
        vectorForResults.push_back(pdir->d_name);
    }
}

问题:如何使用 boots 库检查每个文件的大小(从当前目录)?

我找到了http://en.highscore.de/cpp/boost/filesystem.html上描述的方法

例如:

boost::filesystem::path p("C:\\Windows\\win.ini"); 
std::cout << boost::filesystem::file_size(p) << std::endl; 

有人可以帮助如何在我的 open() 函数中实现 boost 它吗?特别是如何将当前目录路径名分配给变量p,然后遍历文件名。

【问题讨论】:

  • 如果有某种reference...
  • boost::filesystem::path p(path.c_str()) 但没有成功...
  • 您可能没有正确使用pdir。它可能指向静态缓冲区,因此请确保您正在复制它所指向的内容。如果vectorForResults 正在存储指针,那么你就有麻烦了。

标签: c++ boost


【解决方案1】:

这有帮助吗?

Live On Coliru

#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>

namespace fs = boost::filesystem;

int main()
{
    for(auto& f : boost::make_iterator_range(fs::directory_iterator("."), {}))
    {
        if (fs::is_regular(f))
            std::cout << fs::file_size(f) << "\t" << f << "\n";
    }
}

注意"."是当前目录

【讨论】:

  • 当我将第一行更改为: for(auto& f : boost::make_iterator_range(fs::directory_iterator("."))) 非常感谢@sehe!
【解决方案2】:
#include <dirent.h>

void open(std::string path){

    DIR* dir;
    dirent *pdir;

    dir = opendir(path.c_str());
    while (pdir = readdir(dir)){
        std::string p = path + "/" + pdir->d_name;
        vectorForResults.push_back(pdir->d_name);
        std::cout << boost::filesystem::file_size(p) << std::endl;
    }
}

我想这就是你要找的东西。 您不需要创建 boost::filesystem::path 对象。

或者你可以使用C函数stat:http://linux.die.net/man/2/stat

【讨论】:

  • 是的对不起我没有测试代码,我这台电脑上没有c++编译器
猜你喜欢
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多