0

I am fairly new to C++. I have been trying to access the names of files in a specific folder. I'm not sure if I should use a vector or a list. I tried a list, just because that's what I'm used to.

#include <iostream>
#include <string>
#include <fstream>
#include <list>
using namespace std;

list<string> file_list(string file)
{
    list<string> list;
    ifstream files;
    string line;
    files.open(file);
    while (getline(files, line)) {
        list.push_back(line);
    }
    files.close();
    cout << &list << endl;
    return list;
}

When I debug the variable line stays blank and it prints off 0x7fff5fbff6b0. I am trying access my downloads folder. The string variable 'file' is a direct path to it. It opens just fine, but I can't access the file names inside it.

2 Answers2

0

C++ standard library doesn't have a filesystem access library (yet). If you want to enumerate all the files in a folder and your compiler doesn't have the std::experimental::filesystem, you can use boost::filesystem.

Rostislav
  • 3,857
  • 18
  • 30
0

This

cout << &list << endl;

prints out the address of list, that mysterious 0x7fff5fbff6b0, not the contents of list.

To print the contents you need something more like

for (string & str: list)
{
    cout << str << endl;
}

Oh, and lose the ; at the end of

list<string> file_list(string file);

And Duhr. Yeah. Totally missed the point of what OP was trying to do.

Reading a directory like a file doesn't work with a stream. You will have to use a platform-specific method. Give this question a read: How do you iterate through every file/directory recursively in standard C++?

Community
  • 1
  • 1
user4581301
  • 33,082
  • 7
  • 33
  • 54