C/C++ - Locating a user's home directory - SOLVED

Dotan Cohen dotancohen at gmail.com
Thu Feb 10 09:23:41 UTC 2011


On Sun, Jan 30, 2011 at 15:39, David Fletcher <dave at thefletchers.net> wrote:
> //      For the benefit of anybody else who searches Google
> //      to try to find an answer to this question:-
>
> //      Short example
> //      how to write a C/C++ program for Linux to determine
> //      find the home directory of the user who is running it
>
> //      Use the command
> //      g++ -Wall HomeDirTest.cpp -o HomeDirTest
> //      to compile this source
>
> //      Compiled and tested by running as a cron job on an
> //      Ubuntu 10.04 server with the executable file copied
> //      to /usr/local/bin/
>
>
> #include        <stdio.h>
> #include        <string.h>
> #include        <pwd.h>
> #include        <fstream>
>
> using namespace std;
>
> int main(void)
> {
>        ofstream DirTest;
>        int myuid;
>        struct passwd *mypasswd;
>        char TestFileName[30];
>
>        myuid = getuid();
>        mypasswd = getpwuid(myuid);
>
>        strcpy(TestFileName, mypasswd->pw_dir);
>        strcat(TestFileName, "/DirTestOutput");
>
>        DirTest.open(TestFileName);
>        DirTest << "This is a test\n\n";
>        DirTest << "My uid is " << myuid << "\n\n";
>        DirTest.close();
> }
>
>

Hi Dave! I am just starting to learn C++ (I know a touch of C and some
Java and PHP), and this snippet is a great example of useful
real-world code. Do you have any more snippets that you would like to
share? My goal is to ramp up my C++ for Google Summer of Code this
year.

Thanks!


-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com




More information about the ubuntu-users mailing list