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

Ioannis Vranos cppdeveloper at ontelecoms.gr
Thu Feb 10 16:13:08 UTC 2011


On Thu, 2011-02-10 at 11:23 +0200, Dotan Cohen wrote:
> 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/


Comments:


Not needed in this code:

> > #include        <stdio.h>



> > #include        <string.h>
> > #include        <pwd.h>
> > #include        <fstream>


Try using namespace statements in an as small scope as possible. Global
namespace statements is an attempt to defeat the namespace mechanism.


> > using namespace std;
> >
> > int main(void)
> > {
> >        ofstream DirTest;
> >        int myuid;


Keyword struct is not needed, but it is valid.

> >        struct passwd *mypasswd;

> >        char TestFileName[30];
> >
> >        myuid = getuid();
> >        mypasswd = getpwuid(myuid);
> >


strcpy() is too C.


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


A more elegant C++ implementation is the following:

// It creates a DirTestOutput text file in your home directory.

#include <string>
#include <pwd.h>
#include <fstream>

int main(void)
{
	using std::ofstream;
	using std::string;

	ofstream DirTest;

	int myuid;

	passwd *mypasswd;

	string TestFileName;

	myuid = getuid();

	mypasswd = getpwuid(myuid);


	TestFileName= mypasswd->pw_dir;

	TestFileName+= "/DirTestOutput";


	DirTest.open(TestFileName.c_str());

	DirTest << "This is a test\n\n";

	DirTest << "My uid is " << myuid << "\n\n";

	DirTest.close();
}



Another C++ implementation that shows your home directory and UID on the
screen only, is the following:


// It shows your home directory and UID on the screen.

#include <iostream>
#include <pwd.h>
#include <fstream>

int main(void)
{
	using namespace std;

	int myuid;

	passwd *mypasswd;

	myuid = getuid();

	mypasswd = getpwuid(myuid);


	cout<<"\nYour home directory is: "<< mypasswd->pw_dir<< "\n\n"
		<<"Your UID is: "<< myuid<< "\n\n";
}



-- 
Ioannis Vranos

http://www.cpp-software.net





More information about the ubuntu-users mailing list