Directory list into Array

closed account (G26pX9L8)
Hello,

I am trying to get all files in the current directory. After that is should be stored into an array. This is what I have now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <dirent.h>
#include <stdio.h>
#include <iostream.h>

int main(void)
{
  DIR           *d;
  struct dirent *dir;
  char dirlist[] = {};
  int i=0;
  d = opendir(".");
  if (d)
  {
    while ((dir = readdir(d)) != NULL)
    {
      i++;
      //cout<<dir->d_name<<endl;
      dirlist[i] = *dir->d_name;
    }
    cout<<dirlist<<endl;

    closedir(d);
  }

  return(0);
}

There are no errors but its not working as I hoped. I even don't know if I'm using the right code to get a content of a directory. Who can help me?
Last edited on
You don't actually have an array. I'm not sure what you think char dirlist[] = {}; does.

You need to replace it with a container that can grow. There are many, your question suggests a vector, an array that can grow. You're storing strings in the container.
You need to include vector and string as:
1
2
#include <vector>
#include <string> 


You need to replace the old iostream.h with the new iostream as:
1
2
#include <iostream>
using namespace std;


You need to replace char dirlist[] = {}; with vector<string> dirlist;

Finally, you need to put elements into the container. Replace:
dirlist[i] = *dir->d_name;
with:
dirlist.push_back(dir->d_name);
Last edited on
closed account (G26pX9L8)
And how to show the output? If I use the cout I get this error:
C:\cpp_proj\temptest\main.cpp|24|error: no match for 'operator<<' in 'std::cout << dirlist'

And if I use the printf(); a runtime error occurred.

what to do now?
To display an element from vector, use [] operator:
cout <<dirlist[0]; or cout <<dirlist.at(0); // display the first element in vector
Use for loop to display contents of dirslist:
1
2
 for(int i=0;i<dirlist.size();i++)
        cout<<dirlist[i]<<endl;
closed account (G26pX9L8)
tnx its working. I never used vectors before so this is a little new for me.
Or after you feel your own-crafted for loop is not efficient and maybe the STL implementers can do a better job, try below which is lifted off from http://www.cplusplus.com/reference/std/iterator/ostream_iterator/

copy(dirlist.begin(), dirlist.end(), ostream_iterator<string> (cout,"\n"));

Seriously I wonder if the STL implementers can do a "faster" job than our for-loop but Scott Meyers in Effective C++ says it is always good to turn to STL algorithm as it has a "chance" to do a better job than our for-loop as they know the internal implementation of the vector class.

I don't know if I should agree with this recommendation. Anyone dis-agree ? Can a copy algorithm beat a simple for-loop in our case ? Hmmm....

Topic archived. No new replies allowed.