Help understanding code for traversing a file

Hello, I found some code online somewhere for a project I was doing that allows you to read all the files in a certain file directory, however I don't really understand what everything does, and I was hoping someone could point me in the right direction?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  const char* dirName="./lists/"; 
  string path;
  DIR *dir;
  struct dirent *ep;
  char* DirfileName;

  dir = opendir (dirName);

  while ((ep = readdir (dir)))
  {
      DirfileName = ep->d_name;

      cout << DirfileName << endl;
  }

I understand that the "./" in the dirName tells it to start in the directory where the file was saved, I'm more interested in the while loop.
What does (ep = readdir (dir))do?
Also, how does ep->d_name work, since d_name is not defined?

Any help is most appreciated.
closed account (Dy7SLyTq)
god thats archaic c. pretty low level too
Ah okay, well then is there another way to do what this is doing, that is less ehm, archaic? This does have it's flaws...
(It counts a '.' and '..' representing the file tree as a file).
(also throws error:
warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]|
)
Last edited on
code for traversing a file

Actually, what you're showing is code to traverse directory entries in a directory. A directory entry can be either a file or a subdirectory.

What does (ep = readdir (dir))do?

See:

opendir
http://pubs.opengroup.org/onlinepubs/7908799/xsh/opendir.html

readdir
http://pubs.opengroup.org/onlinepubs/7908799/xsh/readdir.html

and, though it's missing from your code fragment:

closedir
http://pubs.opengroup.org/onlinepubs/7908799/xsh/closedir.html

how does ep->d_name work, since d_name is not defined?

ep is a pointer to a dirent struct, which has the following members:

ino_t d_ino file serial number
char d_name[] name of entry

(Do you know about structs? If not, see

Data Structures
http://www.cplusplus.com/doc/tutorial/structures/ )

./

This means use the current working directory

is there another way to do what this is doing, that is less ehm, archaic?

You could use the Boost.Filesytem directory_iterator
http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/reference.html#Class-directory_iterator

(Boost.Filesytem has been proposed for C++ TR2, so it may well turn up in the standard library at some point.)

It counts a '.' and '..' representing the file tree as a file

As alrady said above, readdir is not listing files, it is listing directory entries; these include subdirectories as well as files.

(also throws error:
warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings])

If that's line 11 of the fragment, you should change DirfileName to be a const char*

Andy
Last edited on
Topic archived. No new replies allowed.