1

在继续操作之前,我试图确保用户在正确的组中。出于某种原因,它提供了一个奇怪的编译时错误。

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

bool getGroup() {
    const std::string group = "Controller";

    group *grp = getgrnam(group.c_str());
    if (grp == NULL) {
        ERROR("No group (%s) exists", group.c_str());
        return false;
    }

    passwd *pw = getpwuid(getuid());
    std::string uid(pw->pw_name);

    for (char **member = grp->gr_mem; *member; member++) {
        if (uid.compare(*member) == 0) {
            DEBUG("Matched (%s) in group (%s)", uid.c_str(), group.c_str());
            return true;
        }
    }

    ERROR("Unable to match user (%s) in group (%s)", uid.c_str(), group.c_str());
    return false;
}

编译器抱怨main.cpp:在函数中

bool getGroup():
main.cpp:72: error: ‘grp’ was not declared in this scope

这个错误对应于这一行:

group *grp = getgrnam(group.c_str());

我一直在页面中阅读有关此的文档man,并且我相信我做对了。此外,我在我的代码中看不到任何不正确的内容。也许一双新鲜的眼睛会有所帮助。

谢谢!

4

2 回答 2

2
const std::string group = "Controller";

------------------^^^^^

group *grp = getgrnam(group.c_str());
^^^^^

您不能“隐藏”变量后面的类型并期望它们都起作用。

我将第一个更改groupgroupname,它可以像这样编译:

#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <string>

#define ERROR(...)
#define DEBUG(...)

bool getGroup() {
    const std::string groupname = "Controller";

    group *grp = getgrnam(groupname.c_str());
    if (grp == NULL) {
        ERROR("No group (%s) exists", groupname.c_str());
        return false;
    }

    passwd *pw = getpwuid(getuid());
    std::string uid(pw->pw_name);

    for (char **member = grp->gr_mem; *member; member++) {
        if (uid.compare(*member) == 0) {
            DEBUG("Matched (%s) in group (%s)", uid.c_str(), groupname.c_str());
            return true;
        }
    }

    ERROR("Unable to match user (%s) in group (%s)", uid.c_str(), groupname.c_str());
    return false;
}
于 2013-10-04T19:33:20.320 回答
0

group是在上一行定义的变量,而不是类型。您正在乘以group未声明的grp.

    // define "group"
    const std::string group = "Controller";

    // multiply group with grp, assign to the result
    group * grp = getgrnam(group.c_str());

固定的:

bool getGroup() {
    const std::string group_name = "Controller";

    // multiply group with grp, assign to the result
    group *grp = getgrnam(group_name.c_str());
    if (grp == NULL) {
        ERROR("No group (%s) exists", group_name.c_str());
        return false;
    }

    passwd *pw = getpwuid(getuid());
    std::string uid(pw->pw_name);

    for (char **member = grp->gr_mem; *member; member++) {
        if (uid.compare(*member) == 0) {
            DEBUG("Matched (%s) in group (%s)", uid.c_str(), group_name.c_str());
            return true;
        }
    }

    ERROR("Unable to match user (%s) in group (%s)", uid.c_str(), group_name.c_str());
    return false;
}
于 2013-10-04T19:32:58.563 回答