2013-05-27 27 views
3

我想使用C++從文件夾中讀取一些jpg文件。我搜索了互聯網,並找不到解決方案。我不想使用Boost或其他庫,但只需使用C++函數編寫它。例如,我有40個圖像,在我的文件夾中以"01.jpg, 02.jpg,...40.jpg"命名,我想給出文件夾地址,並讀取這40個圖像並將它們逐個保存在向量中。我嘗試過幾次,但都失敗了。我正在使用Visual Studio。有人可以幫助我嗎?謝謝。如何從C++文件夾中讀取文件?

+1

嘗試findfirstfile和findnextfile在sdk或cfilefind中的mfc。 – Jichao

+1

如何以'for(int i = 1; i <= 40; i ++){...}'開頭?然後閱讀['std :: istringstream'](http://en.cppreference.com/w/cpp/io/basic_istringstream)。 –

+1

查看關於如何使用Win32 API執行此問題的答案:http://stackoverflow.com/questions/15068475/recursive-hard-disk-search-with-findfirstfile-findnextfile-c – Asha

回答

1

我意識到根據你的評論,你已經想出了一個可行的解決方案,使用_sprintf_s。微軟喜歡將其作爲sprintf的一個更安全的替代方案,如果您使用C語言編寫程序,則情況屬實。但在C++中,有更安全構建字符串的方法不需要您管理緩衝區或瞭解它的最大尺寸。如果你想成爲慣用者,我建議你使用_sprintf_s並使用C++標準庫提供的工具。

下面介紹的解決方案使用簡單的for循環和std::stringstream創建文件名並加載圖像。我還包括使用std::unique_ptr進行生命週期管理和所有權語義。根據圖像的使用方式,您可能需要使用std::shared_ptr

#include <iostream> 
#include <sstream> 
#include <iomanip> 
#include <vector> 
#include <stdexcept> 

// Just need something for example 
struct Image 
{ 
    Image(const std::string& filename) : filename_(filename) {} 
    const std::string filename_; 
}; 

std::unique_ptr<Image> LoadImage(const std::string& filename) 
{ 
    return std::unique_ptr<Image>(new Image(filename)); 
} 

void LoadImages(
    const std::string& path, 
    const std::string& filespec, 
    std::vector<std::unique_ptr<Image>>& images) 
{ 
    for(int i = 1; i <= 40; i++) 
    { 
     std::stringstream filename; 

     // Let's construct a pathname 
     filename 
      << path 
      << "\\" 
      << filespec 
      << std::setfill('0') // Prepends '0' for images 1-9 
      << std::setw(2)   // We always want 2 digits 
      << i 
      << ".jpg"; 

     std::unique_ptr<Image> img(LoadImage(filename.str())); 
     if(img == nullptr) { 
      throw std::runtime_error("Unable to load image"); 
     } 
     images.push_back(std::move(img)); 
    } 
} 

int main() 
{ 
    std::vector<std::unique_ptr<Image>> images; 

    LoadImages("c:\\somedirectory\\anotherdirectory", "icon", images); 

    // Just dump it 
    for(auto it = images.begin(); it != images.end(); ++it) 
    { 
     std::cout << (*it)->filename_ << std::endl; 
    } 
}