c ++读取指针的内容

Cas*_*Roy 2 c++ pointers

我是c ++世界的新手,我只是将它用于帮助我工作的litle应用程序,现在,我需要阅读文件夹的内容,列出文件夹内容,我已经创建了一个返回指针的函数文件夹中每个obj的名称,但现在,我不知道如何读取指针的内容只是在控制台中打印它,我的函数看起来像这样

string* listdir (const char *path)
{
    string* result = new string[50]; // limit to 50 obj
    DIR *pdir = NULL;
    pdir = opendir (path);
    struct dirent *pent = NULL;
    if (pdir == NULL)
    { 
        printf ("\nERROR! pdir could not be initialised correctly");
        return NULL;
    } 
    int i = 0;
    while (pent = readdir (pdir))
    {
        if (pent == NULL)
        {
            printf ("\nERROR! pent could not be initialised correctly");
            return NULL;
        }
        //printf ("%s\n", pent->d_name);
        result[i++]= pent->d_name;
    }

    closedir (pdir);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

我一直试图打印teh功能的结果

int main()
{
    string *dirs;
    dirs = listdir("c:\\");
    int i = 0;
    //while(dirs[i])
    //{
            //cout<<dirs[i]<<'\n';
            //++i;
    //}
}
Run Code Online (Sandbox Code Playgroud)

但我真的不知道我在做什么,哈哈,一些帮助将是完美的谢谢

ice*_*ime 5

检查你的while循环条件:dirs[i]是一个std::string.您在布尔上下文中使用字符串对象:您希望std::string转换为bool

我的建议:抛弃固定大小的阵列然后去std::vector.

void listdir(const char *path, std::vector<std::string> &dirs)
{
    /* ... */
    while (pent = readdir (pdir))
    {
        /* ... */
        dirs.push_back(pent->d-name);
    }

    closedir(pdir);
}

int main()
{
    std::vector<std::string> dirs;

    listdir("c:\\", dirs);
    for (std::vector<std::string>::const_iterator it = dirs.begin(), end = dirs.end(); it != end; ++it)
        std::cout << *it << std::endl;
}
Run Code Online (Sandbox Code Playgroud)