【问题标题】:How do I look through my hard drive directories in a C++ program?如何在 C++ 程序中查看我的硬盘目录?
【发布时间】:2012-05-21 14:00:01
【问题描述】:

我正在寻找一个返回特定目录中内容列表的函数。 我得到的最接近的是使用这个:

system("dir");

但这只会打印工作目录的内容,我不能 CD 到其他任何地方。

我使用的是 Windows,我没有计划让它跨平台,所以不用担心。

【问题讨论】:

标签: c++ navigation directory


【解决方案1】:

看下面这个直接从this page复制过来的例子。它使用boost::filesystem,因此适用于所有主要系统。

int main(int argc, char* argv[])
{
    path p (/* Specify a directory here */);

    try
    {
        if (exists(p))    // does p actually exist?
        {
            if (is_regular_file(p))        // is p a regular file?   
                cout << p << " size is " << file_size(p) << '\n';
            else if (is_directory(p))      // is p a directory?
            {
                cout << p << " is a directory containing:\n";

                copy(directory_iterator(p), directory_iterator(), // directory_iterator::value_type
                  ostream_iterator<directory_entry>(cout, "\n")); // is directory_entry, which is
                                                                  // converted to a path by the
                                                                  // path stream inserter
            }
            else
                cout << p << " exists, but is neither a regular file nor a directory\n";
        }
        else
            cout << p << " does not exist\n";
    }

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

    return 0;
}

【讨论】:

  • 这就是我要找的:3 我不明白的一个重要部分是 argv[1] 是什么。通过 uni,他们告诉我的只是“你可以把它作为 main 的争论,但它并没有真正做任何事情,所以不要打扰”。我现在认为它有一些目的哈哈。
  • @Magicaxis 等等,我会修改我的答案。顺便说一句,假设您的可执行文件是listDir.exe,然后在命令行中输入listDir.exe C:\ExampleDir,然后输入argv[0] = listDir.exeargv[1] = C:\ExampleDirargc = 2。谷歌command line arguments in c / c++ 你会知道更多,:)。如果这是您的答案,请标记它。
  • 在这个网站上也可以看到C++ - int main(int argc, char **argv) :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
相关资源
最近更新 更多