Help understanding code for traversing a file

Jul 2, 2013 at 5:12am
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.
Jul 2, 2013 at 6:07am
closed account (Dy7SLyTq)
god thats archaic c. pretty low level too
Jul 2, 2013 at 7:01am
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 Jul 2, 2013 at 7:28am
Jul 2, 2013 at 7:56am
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 Jul 2, 2013 at 8:08am
Topic archived. No new replies allowed.