【问题标题】:C++ IO with Hard Drive带硬盘的 C++ IO
【发布时间】:2011-02-15 17:45:38
【问题描述】:

我想知道是否有任何一种便携式 (Mac&Windows) 读写硬盘驱动器的方法超出 iostream.h,特别是获取文件夹中所有文件的列表、移动文件等功能等。

我希望周围会有像 SDL 这样的东西,但到目前为止我还没有找到太多东西。

有什么想法吗??

【问题讨论】:

    标签: c++ iostream hard-drive


    【解决方案1】:

    Boost Filesystem 可能是你想要的吗?

    【讨论】:

    【解决方案2】:

    我也是boost::filesystem 的粉丝。写你想要的东西需要最少的努力。下面的例子(只是为了让你感受一下它的样子),要求用户输入一个路径和一个文件名,它将获取所有具有该名称的文件的路径,无论它们是否在根目录中,或在该根目录的任何子目录中:

    #include <iostream>
    #include <string>
    #include <vector>
    #include <boost/filesystem.hpp>
    using namespace std;
    using namespace boost::filesystem;
    
    void find_file(const path& root,
        const string& file_name,
        vector<path>& found_files)
    {
        directory_iterator current_file(root), end_file;
        bool found_file_in_dir = false;
        for( ; current_file != end_file; ++current_file)
        {
            if( is_directory(current_file->status()) )
                    find_file(*current_file, file_name, found_files);
            if( !found_file_in_dir && current_file->leaf() == file_name )
            {
                    // Now we have found a file with the specified name,
                    // which means that there are no more files with the same
                    // name in the __same__ directory. What we have to do next,
                    // is to look for sub directories only, without checking other files.
                    found_files.push_back(*current_file);
                    found_file_in_dir = true;
            }
        }
    }
    
    int main()
    {
        string file_name;
        string root_path;
        vector<path> found_files;
    
        std::cout << root_path;
        cout << "Please enter the name of the file to be found(with extension): ";
        cin >> file_name;
        cout << "Please enter the starting path of the search: ";
        cin >> root_path;
        cout << endl;
    
        find_file(root_path, file_name, found_files);
        for( std::size_t i = 0; i < found_files.size(); ++i)
                cout << found_files[i] << endl;
    }
    

    【讨论】:

      【解决方案3】:

      没有原生 C++ 方法可以跨平台遍历目录结构或列出目录中的文件。它只是没有内置在语言中。 (有充分的理由!)

      最好的选择是使用代码框架,那里有很多不错的选择。

      Boost Filesystem

      Apache Portable Runtime

      Aaa 和我个人最喜欢的 - Qt

      虽然,如果您使用它,则很难使用它的文件系统部分。您几乎必须将整个应用程序移植到 Qt 特定类。

      【讨论】:

      • 好吧,“它不是内置的”可能是暂时的。我认为 boost.FileSystem 会在 TR2 上成为标准,但从那以后就没有听到任何消息......
      猜你喜欢
      • 2023-04-04
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2011-08-06
      • 2016-03-15
      • 2013-11-21
      • 2010-11-01
      相关资源
      最近更新 更多