代码之家  ›  专栏  ›  技术社区  ›  Tomas

具有硬盘驱动器的C++ IO

  •  4
  • Tomas  · 技术社区  · 15 年前

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

    我本来希望周围会有类似SDL的东西,但到目前为止我还没能找到多少。

    有什么想法吗??

    3 回复  |  直到 14 年前
        1
  •  3
  •   kurige    15 年前

    没有跨平台的方式遍历目录结构或目录文件的本机C++方式。它并不是语言的组成部分。(有充分的理由!)

    你最好的选择是使用一个代码框架,并且有很多好的选择。

    Boost Filesystem

    Apache Portable Runtime

    aa和我的个人最爱- Qt

    尽管如此,如果你用这个很难 只是 使用它的文件系统部分。您几乎必须将整个应用程序移植到Qt特定的类上。

        2
  •  11
  •   Smashery    15 年前

    可以 Boost Filesystem 可能是你想要的?

        3
  •  4
  •   Khaled Alshaya    15 年前

    我是个迷 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;
    }