Printing the contents of an user inserted direcory path, using dirent in C++

248 Views Asked by At

Total newbie in c++ Here's my problem. I am trying to write a c++ prog that reads a path from a user and prints the contents of the direcory on the screen. I am able to read a directory and print it but I cannot make it read from the outside.

#include <iostream>
#include <dirent.h>
using namespace std;


int main()
{

struct dirent *entry;
int files = 0;
DIR *folder;
const char *path;
path = userdir();

folder = opendir(path);
if (folder == NULL)
{
    cout << "Unable to open the directory \n\n";
    return(1);
}
else
{
    cout << "Directory opened\n\n";
    
}
while ((entry=readdir(folder))) 
{
    files++;
    cout << "File " << files << " " << entry->d_name << endl;
}
closedir(folder);
return(0);
}

I just want to create a function that reads the path from the user and passes the value to the main function, but somehow the fact that "path" is a const char doesn't allow me to do it.

Apologies for my ignorance...my experience in c++ is just 2 days....

OK

I managed to get a bit further, and added the following funcion

char * userdir()
{
    char * ppath;
    cout << "\nInsert path\n";
    getline(cin,ppath);
    return ppath;
}

And now the error I get is : In function 'char* userdir()': [Error] no matching function for call to 'getline(std::istream&, char*&)'

NB: funcion placed before int main()

1

There are 1 best solutions below

0
On

Since this is C++, you can do the following to read the path:

cin >> path;