Go to Google Groups Home    comp.os.linux.misc
Mike releases the "home" command under the GPL

Tim Smith <reply_in_gr...@mouse-potato.com>

In article <3d6111f1.0401241749.22dc5...@posting.google.com>, Mike Cox wrote:
> #include <iostream>

> int main()
> {
>    char* name= new char[strlen(getlogin()) + 1];
>    strcpy(name,getlogin());

Why call getlogin twice?

    char * login_name = getlogin();
    int name_len = strlen(login_name);
    char * name = new char[name_len+1];
    strcpy(name,login_name);

or better yet, use std::string:

    std::string name(getlogin());

>    if(strcmp(name, "root") == 0)
>    {
>            std::cout<<"going to home directory...\n";
>            FILE* pipe;
>            pipe =  popen("cd /root/", "w");    
>            pclose(pipe);
>    } else{
>            char* base = "/home/";
>            strcat(base, name);

String constants like "/home/" aren't guaranteed to be in writable memory.
If it is, you've just trashed whatever followed it.  You want this:

                char * base = new char[name_len + 7];
                strcpy( base, "/home/" );
                strcat( base, name );

But wait...what is the point of the "name" variable?

                char * base = new char[name_len + 7];
                strcpy( base, "/home/" );
                strcat( base, login_name );

Or, doing this right and using std::string:

                std::string base = "/home/" + std::string(getlogin());

>            FILE* bong;
>            std::cout<<"going to home directory...\n";
>            bong = popen(base,"w");

Oops.  You left out the "cd".  Change "/home/" in the earlier stuff to
"cd /home/".

>            pclose(bong);
>    }

>    delete [] name;
>    return 0;
> }

After you build this and it doesn't work, and you finally figure out why, you
will feel really dumb.  However, don't feel bad.  Dennis Ritchie made the
same mistake when he implemented the "cd" command way back on the earliest
Unix that had a shell and a filesystem with directories. :-)

--
--Tim Smith