获取windows所有用户名

时间:2021-02-09 18:23:33
#include <LM.h> #pragma comment(lib, "netapi32.lib") // See more: http://msdn.microsoft.com/en-us/library/windows/desktop/aa370652(v=vs.85).aspx void GetAllUserName(std::vector<std::wstring> & allUserName) { LPUSER_INFO_1 pBuf = NULL; LPUSER_INFO_1 pTmpBuf; DWORD dwLevel = 1; DWORD dwEntriesRead = 0; DWORD dwTotalEntries = 0; DWORD dwResumeHandle = 0; DWORD dwPrefMaxLen = MAX_PREFERRED_LENGTH; NET_API_STATUS nStatus; LPTSTR pszServerName = NULL; do { nStatus = NetUserEnum((LPCWSTR) pszServerName, dwLevel, FILTER_NORMAL_ACCOUNT, // global users (LPBYTE*)&pBuf, dwPrefMaxLen, &dwEntriesRead, &dwTotalEntries, &dwResumeHandle); if ((nStatus == NERR_Success) || (nStatus == ERROR_MORE_DATA)) { if ((pTmpBuf = pBuf) != NULL) { for (DWORD i = 0; i < dwEntriesRead; i++) { if (pTmpBuf == NULL) { fprintf(stderr, "An access violation has occurred\n"); break; } allUserName.push_back(pTmpBuf->usri1_name); pTmpBuf++; } } } else fprintf(stderr, "A system error has occurred: %d\n", nStatus); if (pBuf != NULL) { NetApiBufferFree(pBuf); pBuf = NULL; } } while (nStatus == ERROR_MORE_DATA); // end do // Check again for allocated memory. if (pBuf != NULL) NetApiBufferFree(pBuf); }