2010-05-05 122 views
4

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

我希望能有像SDL一样的东西,但到目前为止我一直无法找到太多东西。

任何想法??

回答

3

没有本地C++方法来遍历目录中的一个目录结构或列表文件中跨平台的方式。它只是没有内置到语言中。 (有充分的理由!)

你最好打赌是去一个代码框架,并有很多很好的选择。

Boost Filesystem

Apache Portable Runtime

Aaaand我个人的最爱 - Qt

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

+0

3种可能解决方案的奖励积分! – Tomas 2010-05-07 14:51:14

+0

那么,“这是不是有原因内置”可能是暂时的。我认为boost.FileSystem会在TR2中进入标准版,但自从...之后没有听到任何声音...... – rubenvb 2011-01-26 20:31:03

11

难道Boost Filesystem可能是你在追求什么?

+1

链接到更新的版本(1.42)http://www.boost.org/doc/libs/1_42_0/libs/filesystem/doc/index.htm – 2010-05-05 02:04:34

+0

谢谢 - 我已经更新了我的答案以链接到那个。 – Smashery 2010-05-05 05:38:12

4

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