我試圖創建一個函數來獲得使用在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