关于我使用Boost库的第一个程序的问题(例外,长路径)

时间:2010-11-24 00:55:48

标签: c++ boost boost-filesystem

我正在尝试用C ++编写我的第一个程序,我需要使用Boost库。我正在尝试编写一个递归遍历目录树的程序,并返回最新和最旧文件的日期。

这就是我现在的位置:

#define BOOST_FILESYSTEM_VERSION 3

#include "boost/filesystem.hpp"
#include <iostream>
#include <ctime>


using namespace std;
namespace fs = boost::filesystem;


int main() {
 fs::recursive_directory_iterator it_end;
 fs::recursive_directory_iterator it_dir("e:\\");
 fs::path p;

 time_t oldest( time(NULL) );
 time_t newest(0);

 try {
  for ( ; it_dir != it_end; ++it_dir ) {
   p = *it_dir;
   try {
    time_t t( last_write_time(p) );
    if (t<oldest) oldest=t;
    if (t>newest) newest=t;
    if (fs::is_directory(p)) cout << (p) << " " << t << endl;
   } 

   catch (const fs::filesystem_error& ex) {
    cout << "\n" << ex.what() << "\n";
   }
  }
 }

 catch (const fs::filesystem_error& ex) {
  cout << "\n" << ex.what() << "\n";
 }

 cout << "\nOldest: " << ctime(&oldest);
 cout << "Newest: " << ctime(&newest) << endl;

 return 0;
}

我遇到的问题是:

1.当我遇到太长的路径(我认为超过256或260个字符)时,会出现错误:

boost::filesystem::last_write_time: The system cannot find the path specified:

2.当我遇到一个不可访问的目录,比如“系统卷信息”时,我还有两个:

boost::filesystem::last_write_time: Access is denied: "e:\System Volume Information"

boost::filesystem::directory_iterator::construct: Access is denied: "e:\System Volume Information"

如何修改上面的代码来处理Windows下的长路径名?这样做真的很难吗?有些程序,例如Total Commander,对于长路径没有问题,但许多程序仍有。

更重要的问题是,我如何才能真正使上述代码工作(不关心长路径)。问题是当for ( ; it_dir != it_end; ++it_dir )遇到一个不可访问的目录时,它会抛出异常,为了捕获这个异常,我需要定义外部catch。但是当我在外面时,这意味着 for 循环不会继续。所以这意味着上面的代码可以工作到第一个无法访问的文件夹。它会引发异常并结束。

在抛出异常后,有没有办法重新进入 for 循环? 我的想法是在catch中执行++ it_dir并再次启动for循环。但是我怎么能再次开始呢? Shell我把它移到一个单独的函数?

很抱歉,如果我的理解不明确,这是我的第一个项目。我之前从未使用过C ++,但我正在尽我所能!

编辑:

还有其他答案吗?问题是,catch不在里面循环中“无法访问”的错误。我怎样才能让它在里面工作?这是产生错误的最小代码。有没有办法在for循环中捕获这个错误?或者以使用it_dir ++跳过不可访问元素后可以继续捕获它?

int main() {
 fs::recursive_directory_iterator it_end;
 fs::recursive_directory_iterator it_dir("e:\\");

  for ( ; it_dir != it_end; ++it_dir ) {
  //something here
  }
}

2 个答案:

答案 0 :(得分:3)

事实证明这是一个提升中的错误。我找到了一张bug支持票,并为此做出了贡献。

答案 1 :(得分:0)

将try / catch放在for循环中......

相关问题