2016-05-23 7 views
0

すべてのファイル名を配列に取得しようとしています。しかし、すべてのファイル名を読み込んだあと、配列には最後のファイル名しかありません。配列にファイル名を格納するVC++

#include <Windows.h> 
#include <strsafe.h> 
#include <iostream> 


int main() { 

    WIN32_FIND_DATA ffd; 
    HANDLE handle = INVALID_HANDLE_VALUE; 
    TCHAR *directory = L"D:/*.*"; 
    LPCWSTR filenames[30] ; 
    handle = FindFirstFile(directory, &ffd); 
    int count = 0; 
    if (handle != INVALID_HANDLE_VALUE) { 
     OutputDebugString(ffd.cFileName); 
     do { 
      filenames[count++] = ffd.cFileName; 

      OutputDebugString(filenames[count -1]); 
     } while (FindNextFile(handle, &ffd) != 0); 

    } 
    else { 
     OutputDebugString(L"Nothing to display \n"); 
    } 

    for (int i = 0; i < 10; i++) { 
     OutputDebugString(filenames[i]); 
    } 
    FindClose(handle); 
    getchar(); 
    return 0; 
} 

私はこのコードを持っている問題は何..です事前に 感謝..以上

答えて

3
LPCWSTR filenames[30]; 

は文字の配列です。これは文字列の配列ではありません。また、ファイル名を含めるには短すぎます。MAX_PATHにすることができます。

wchar_t **buf;を使用して文字列の配列を作成するか、std::vectorstd::stringを使用します。

ファイルハンドルが無効な場合は閉じないでください。

宿題などの一部でない限り、TCHARは使用しないでください。 Windowsの場合はwchar_tを使用してください。

#include <Windows.h> 
#include <iostream> 
#include <vector> 
#include <string> 

int main() 
{ 
    std::vector<std::wstring> vec; 

    wchar_t *directory = L"D:/*.*"; 
    WIN32_FIND_DATA ffd; 
    HANDLE handle = FindFirstFile(directory, &ffd); 
    if (handle != INVALID_HANDLE_VALUE) 
    { 
     do { 
      vec.push_back(ffd.cFileName); 
     } while (FindNextFile(handle, &ffd)); 
     FindClose(handle); 
    } 
    else 
    { 
     OutputDebugString(L"Nothing to display \n"); 
    } 

    for (unsigned int i = 0; i < vec.size(); i++) 
    { 
     OutputDebugString(vec[i].c_str()); 
     OutputDebugString(L"\n"); 
    } 

    getchar(); 
    return 0; 
} 
関連する問題