Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ read content of a pointer

Tags:

c++

pointers

i'm new in c++ world, i just use it for litle app that help me in my work, now, i need to read the content of a folder, list the folder content, i've made a function that return a pointer with the name of every obj in the folder, but now, i don't know how to read the content of the pointer to just print it in a console, my function look like this

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

i've been trying to print the result of teh function

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

but i really don't know what i'm doing, lol, some help would be perfect thanks

like image 797
Castro Roy Avatar asked Nov 25 '25 07:11

Castro Roy


2 Answers

Examine your while loop condition : dirs[i] is a std::string. You are using a string object in a boolean context : would you expect std::string to convert to bool ?

My recommendation : ditch the fixed sized array and go for 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;
}
like image 104
icecrime Avatar answered Nov 27 '25 21:11

icecrime


int main()
{
    string *dirs;
    dirs = listdir("c:\\");
    for (int i = 0; i < 50 && dirs[i].size() > 0; ++i)
    {
            cout << dirs[i] << '\n';
    }
}

dirs is a pointer to an array, so you can index it like an array. You created an array of 50, so you need to limit yourself to 50 here too. Since you might not have populated the whole array, the .size() check allows the printing loop to stop early.

like image 20
Tim Avatar answered Nov 27 '25 20:11

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!