1
#include <string>
#include <stdio.h>
#include <pwd.h>

std::string impPath()
{
    char *name;
    struct passwd *pass;
    pass = getpwuid(getuid());
    name = pass->pw_name;

    std::string PATH = "/home";
    PATH.append("/");
    PATH.append(name);

    return PATH;
}

I need to know username of the user. In order to do this. I am using getpwuid() but I am getting this error.

/home/shobhit/Desktop/file.cpp:15: error: 'getuid' was not declared in this scope
 pass = getpwuid(getuid());
                        ^

I just couldn't figure out what is the reason that getuid is not declared in this scope. I think I have included all the necessary header files.(yami's comment on R's answer getlogin() c function returns NULL and error "No such file or directory" I have tried searching on the web but couldn't find any relevant answer.

shobhit
  • 91
  • 3
  • 12
  • 1
    Did you try `man getuid`? – alk Jun 16 '18 at 13:47
  • 2
    Also C and C++ are not Java. You do not "*include libraries*", but header files, which in fact are source code. *If* libraries are used, then they are *linked*, this is done later, *after compilation* of the source code is done. – alk Jun 16 '18 at 13:48
  • Yeah thanx I have edited my question. – shobhit Jun 17 '18 at 06:16

2 Answers2

9

man getuid:

SYNOPSIS

#include <unistd.h>
#include <sys/types.h>

uid_t getuid(void);
uid_t geteuid(void);

You're missing those includes.

Community
  • 1
  • 1
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • what is the meaning of these lines uid_t getuid(void); uid_t geteuid(void); – shobhit Jun 17 '18 at 07:30
  • 1
    @shobhit They're function declarations. It's how manual pages show you the type and name of an entity. It means "by including these headers, you get access to `getuid` (a function taking no arguments and returning a `uid_t`) and `geteuid` (a function taking no arguments and returning a `uid_t`)." – melpomene Jun 17 '18 at 08:20
  • @shobhit Yes, that's what this documentation shows you. – melpomene Jun 17 '18 at 08:34
  • @shobhit I don't think it was a good question. Your code sample is neither complete (what is `"impfile_path.h"`?) nor minimal (all of the `std::string` and `getpwuid` stuff is irrelevant). You claim "*I have included all the necessary header files*" without justification (and is it turns out, your claim is wrong). The question shows no research effort (why do you think you've included all the necessary headers? how did you determine the required headers?). I think it's unlikely to be helpful for others. – melpomene Jun 17 '18 at 08:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173290/discussion-between-shobhit-and-melpomene). – shobhit Jun 17 '18 at 08:58
1

getuid() is not present in pwd.h. See http://pubs.opengroup.org/onlinepubs/7908799/xsh/pwd.h.html

yakobyd
  • 572
  • 4
  • 12