我试图创建一个函数来获得使用在C try和catch方法++用户名。不幸的是,这段代码不起作用,并且我的应用程序在尝试运行时关闭。创建一个函数来获取使用try和catch方法的用户名在C++
QString UserInfo::getFullUserName()
{
DBG_ENTERFUNC(getFullUserName);
QString result;
qDebug("trying to get the username");
try
{
struct passwd fullUserData=*getpwnam(getUserName().toLatin1());
result = fullUserData.pw_gecos;
// it is the first of the comma seperated records that contain the user name
result = result.split(",").first();
if (result.isEmpty())
{
result = getUserName();
}
}
catch (...)
{
qDebug("exception caught");
}
qDebug() << result;
#endif
DBG_EXITFUNC;
return result;
}
问题发生在这行代码中,因为我已将打印后的打印文件放在打印机后面,永远不会到达。
struct passwd fullUserData=*getpwnam(getUserName().toLatin1());
有没有人知道这里有什么问题?
*编辑--------
这里是我的功能getUserName()
QString UserInfo::GetUserName()
{
DBG_ENTERFUNC(GetUserName);
QString result;
foreach (QString environmentEntry, QProcess::systemEnvironment())
{
QString varName = environmentEntry.section('=',0,0);
QString varValue = environmentEntry.section('=',1,1);
if (varName == "USER" || varName == "USERNAME")
{
result = varValue;
}
}
DBG_EXITFUNC;
return result;
}
您是否有任何异常消息? –
如果找不到名称(或发生其他错误),getpwnam将返回一个空指针。在尝试解除引用之前,您需要检查它。 – Mat