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

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


On Thu, 2011-02-10 at 18:13 +0200, Ioannis Vranos wrote:

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

And more compact versions, by using object definitions at the place they
are first needed (and omitting the DirTest.close() statement, since it
is at the end of main() anyway), are the following:


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

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

int main(void)
{
	using std::string;
	
        int myuid = getuid();

        passwd *mypasswd = getpwuid(myuid);

        string TestFileName= string(mypasswd->pw_dir)+ "/DirTestOutput";

        std::ofstream DirTest(TestFileName.c_str());

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

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



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

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

int main(void)
{
     int myuid = getuid();

     passwd *mypasswd = getpwuid(myuid);

     std::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