首页 > 解决方案 > 在 C++ 中使用 dirent 打印用户插入的目录路径的内容

问题描述

C ++中的总新手这是我的问题。我正在尝试编写一个 c++ prog,它从用户那里读取路径并在屏幕上打印目录的内容。我能够读取目录并打印它,但我无法从外部读取它。

#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);
}

我只想创建一个从用户读取路径并将值传递给主函数的函数,但不知何故,“路径”是一个 const char 的事实不允许我这样做。

为我的无知道歉......我在 C++ 方面的经验只有 2 天......

好的

我设法走得更远,并添加了以下功能

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

现在我得到的错误是:在函数 'char* userdir()': [Error] no matching function for call to 'getline(std::istream&, char*&)'

注意:函数放在 int main() 之前

标签: c++dirent.h

解决方案


由于这是 C++,您可以执行以下操作来读取路径:

cin >> path;

推荐阅读