On Thu, 30 Oct 2003 07:53:35 -0600
Rick Sivernell <[EMAIL PROTECTED]> wrote:

> On Thu, 30 Oct 2003 06:25:39 -0600
> "Vu Pham" <[EMAIL PROTECTED]> wrote:
> 
> > 
> > ----- Original Message ----- 
> > From: "James McDonald" <[EMAIL PROTECTED]>
> > To: <[EMAIL PROTECTED]>
> > Sent: Thursday, October 30, 2003 5:57 AM
> > Subject: Re: username / id
> > 
> > 
> > > Vu Pham wrote:
> > > > Hi all,
> > > >
> > > > Is there any function to get the user name if uid is known, and vice
> > versa ?
> > > > Similar for group.
> > > >
> > > > Thanks,
> > > >
> > >
> > > cat /etc/passwd | grep ^.*:x:500: | awk -F: '{print $1}'
> > > cat /etc/passwd | grep ^.*:x:[0-9]*:500 | awk -F: '{print $1}'
> > >
> > > This is probably not what you want but it does return a name from uid
> > > or gid...
> > 
> > Oh, that works. I would like to know if there is an API so that I can
> > use it in my C app, or do I need to run some commands like your
> > suggestion and capture the output.
> > 
> > Thanks, James.
> > 
> > Vu
> > 
> > _______________________________________________
> > Linux-users mailing list
> > [EMAIL PROTECTED]
> > Unsubscribe/Suspend/Etc ->
> > http://smtp.linux-sxs.org/mailman/listinfo/linux-users
> Vu
> 
>    use exec and put the cat .... in a string. the exec will execute this
>    from
> code.

It really is not necessary to program via exec to read a file. Try the
attached code.

Put it in /tmp. Compile with 'make qq', Run as ./qq


-- 
+����������������������������+�������������������������������+
� Roger Oberholtzer          �   E-mail: [EMAIL PROTECTED]        �
� OPQ Systems AB             �      WWW: http://www.opq.se/  �
� Erik Dahlbergsgatan 41-43  �    Phone: Int + 46 8   314223 �
� 115 34 Stockholm           �   Mobile: Int + 46 733 621657 �
� Sweden                     �      Fax: Int + 46 8   302602 �
+����������������������������+�������������������������������+
#include <stdio.h>

char *myGetUserName(int target) {

        FILE *pwdfile;
        static char name[80];

        if (!(pwdfile = fopen("/etc/passwd", "r"))) return(0);

        while (1)  {
        
                char aline[256];
                int uid;

                if (!fgets(aline, 200, pwdfile)) { name[0] = 0; break; }

                sscanf(aline,   "%*[^:]:"       // login (skip)
                                "%*[^:]:"       // group (skip)
                                "%d:"           // uid
                                "%*d:"          // gid (skip)
                                "%[^:]",        // name
                                &uid, name);

                if (uid == target) break;
        }

        fclose(pwdfile);
        return(name);
}

main ()
{
        printf("uid 500 is %s\n", myGetUserName(500));
        printf("uid 200 is %s\n", myGetUserName(200));
}
_______________________________________________
Linux-users mailing list
[EMAIL PROTECTED]
Unsubscribe/Suspend/Etc -> http://smtp.linux-sxs.org/mailman/listinfo/linux-users

Reply via email to