1

I am new in c++ . And i want to write a function which takes names from folder.

for example i have a folder which name is C:\TEST and in this folder i have lots of text.txt files i want to store all .txt files name in a string array.

Anybody could help me about this issue.

i tried something like this but i failed

const int arr_size = 10;
some_type src[arr_size];
// ...
some_type dest[arr_size];
std::copy(std::begin(src), std::end(src), std::begin(dest));
Paul R
  • 208,748
  • 37
  • 389
  • 560
goGud
  • 4,163
  • 11
  • 39
  • 63
  • You can explore in stack itself. there are so many soln. [see here][1] [1]: http://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files-in-a-directory-using-c-or-c – I.P Aug 23 '13 at 09:21

2 Answers2

3

Using boost filesystem:

#include<vector>
#include<string>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main(int argc, char* argv[])
{
    vector<string> fnames; //your filenames will be stored here

    path p (argv[1]);   // C:\TEST
    directory_iterator di(p);
    directory_iterator di_end;

    while(di != di_end)
    {
        fnames.push_back( di->path().filename().string() );
        ++di;
    }
}

Specify C:\TEST as the command line argument to the program above.

cpp
  • 3,743
  • 3
  • 24
  • 38
0
TCHAR szDir[MAX_PATH]; 
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE; 

hFind = FindFirstFile(szDir, &ffd);

if (INVALID_HANDLE_VALUE != hFind) 
{
 do
  {
   if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
     // You can do a recursive search here, the current file is a directory
    }
   src[arr_size] = ffd.cFileName;
   arr_size++;
  }
  while (FindNextFile(hFind, &ffd) != 0);


  FindClose(hFind);
}
Pankaj
  • 2,618
  • 3
  • 25
  • 47
  • Is that Windows API? He wasn't looking for a strictly Windows solution - he was looking for C++, which to me implies something moderately cross-platform. – SevenBits Aug 23 '13 at 14:41
  • @SevenBits, He put the tags of C++ and Windows. – Pankaj Aug 23 '13 at 15:48
  • So? Maybe he put that tag because he's compiling for that platform. Maybe he's compiling on Windows, but still needs something portable. Who knows? He asked for **C++** - not Windows API (besides, Windows API is written in C, and while I know you can compile C in C++, because he asked for C++, I assume he wants a feature using C++ libraries). – SevenBits Aug 24 '13 at 02:00