How to retrieve current Windows user login using C? - c

I'm new to C. How can i retrieve the current user logged into Windows using C?
I know you can do this in C++ by Environment::UserName, but have no idea how to do it in C.
Thanks :)

You can use GetUserName:
#include <windows.h>
#include <Lmcons.h>
TCHAR username[UNLEN+1];
DWORD len = UNLEN+1;
if (GetUserName(username, &len))
{
//do something with username
}

Related

How to get Windows username and use it in a system function [duplicate]

I want to access the user name in the Windows using C programming and use that name to create the path to the particular file like "c:\users\john\Roaming.....and so on". So for every system user name e.g "john" is different. Help me to find the user name at run time.
#include <stdio.h>
int main(void)
{
printf("%s\n", getenv("USERPROFILE")); // Print user's home directory.
return 0;
}
To get the user name instead of the home path replace USERPROFILE with USERNAME.
What you are looking for, here, is probably more SHGetKnownFolderPath. The function lets you find per-user special folders. This is preferred to querying usernames because the home folder may not have the same name as the user.
WSTR* location;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, NULL, &location);
if (SUCCEEDED(hr))
{
// location contains the folder path
// call CoTaskMemFree to free up the memory once you're done with it
CoTaskMemFree(location);
}
The list of so-called known folders is available here.
The function to get user name on windows is GetUserName
This answer, probably, will help you too.
you could use the following code to get the Username.
#include <stdlib.h>
void main(void)
{
//following gets the appdata folder
char szAppData[1024];
char * szBufer = 0;
szBufer = getenv ("APPDATA");
if (szBufer != NULL)
{
strcpy(szBufer , szAppData);
}
//following code gets the user name
char szOSUserName[1024];
szBufer = getenv ("USERNAME");
if (szBufer != NULL)
{
strcpy(szBufer , szOSUserName);
}
}
You can get the name of the current user with GetUserName:
#include <Windows.h>
#include <Lmcons.h>
#include <stdio.h>
int main()
{
char name[UNLEN + 1];
DWORD cch = UNLEN + 1;
if (GetUserName(name, &cch))
{
char cmd[100 + UNLEN + 1];
sprintf(cmd, "echo The username is \"%s\"", name); // Silly demo command
system(cmd);
}
return 0;
}
Use GetUserNameEx if you want the name in a specific format.
If you need to get the path to a special folder like "My Documents" or "Desktop" you should use the special folder functions like SHGetFolderPath or SHGetKnownFolderPath.
%USERNAME% will give you the username, but a better solution is to store it on %USERPROFILE%\\Desktop\\key.txt to at least make it OS-independent.
And an even better solution would be not to store private information on the users' desktops. Or anywhere.

How to create shortcut with Win32 API and c language

I want to write a program to create a shortcut for a specific file by using win32 API in c. my IDE is visual studio 2010.
I found this page but its sample just not compile and return many errors.
I also find this code but this always create a link with Target: "D:\Desktop\㩣睜湩潤獷湜瑯灥摡攮數" and I don't know why.
can someone tell me why the sample code of Microsoft is not working or the second one return something in Chinese shape language and also with wrong and constant location for any argument?
This is my code for MSDN sample:
#include "stdafx.h"
#include "windows.h"
#include "winnls.h"
#include "shobjidl.h"
#include "objbase.h"
#include "objidl.h"
#include "shlguid.h"
void _tmain(int argc, TCHAR *argv[])
{
CreateLink(argv[1],__argv[2],argv[3]);
}
HRESULT CreateLink(LPCWSTR lpszPathObj, LPCSTR lpszPathLink, LPCWSTR lpszDesc)
{
HRESULT hres;
IShellLink* psl;
// Get a pointer to the IShellLink interface. It is assumed that CoInitialize
// has already been called.
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
if (SUCCEEDED(hres))
{
IPersistFile* ppf;
// Set the path to the shortcut target and add the description.
psl->SetPath(lpszPathObj);
psl->SetDescription(lpszDesc);
// Query IShellLink for the IPersistFile interface, used for saving the
// shortcut in persistent storage.
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
if (SUCCEEDED(hres))
{
WCHAR wsz[MAX_PATH];
// Ensure that the string is Unicode.
MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH);
// Add code here to check return value from MultiByteWideChar
// for success.
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(wsz, TRUE);
ppf->Release();
}
psl->Release();
}
return hres;
}
and the errors are:
1 error C1083: Cannot open include file: 'stdafx.h' and
2 IntelliSense: cannot open source file "stdafx.h"
CreateLink(argv[1],__argv[2],argv[3]);
This call looks weird. You are using argv[] for two LPCWSTR (const wchar_t *) parameters, but are using __argv[] for an LPCSTR (const char *) parameter. You should change the 2nd parameter to LPCWSTR to match the other parameters, and then use argv[] instead of __argv[].
The TCHAR-based IShellLink works with LP(C)WSTR string parameters, and LP(C)TSTR is LP(C)WSTR when compiling for Unicode. Which you are obviously doing, given that you are passing TCHAR-based argv[] values to LPCWSTR parameters, which will only compile if TCHAR is wchar_t.
IPersistFile::Save() takes only a Unicode string as input, regardless of what TCHAR maps to. You are converting the char* value from __argv[] from ANSI to Unicode, so you may as well just get a Unicode string from argv[] to begin with, and omit the call to MultiByteToWideChar() altogether.
There is no good reason to mix ANSI and Unicode strings like this. This is something the MSDN example is getting wrong.
And since your function parameters are working with Unicode strings, you should use the IShellLinkW interface directly instead of the TCHAR-based IShellLink interface.
Try this:
#include "stdafx.h"
#include "windows.h"
#include "shobjidl.h"
#include "objbase.h"
#include "objidl.h"
#include "shlguid.h"
HRESULT CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink, LPCWSTR lpszDesc)
{
HRESULT hres;
IShellLinkW* psl;
// Get a pointer to the IShellLink interface. It is assumed that CoInitialize
// has already been called.
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLinkW, (LPVOID*)&psl);
if (SUCCEEDED(hres))
{
IPersistFile* ppf;
// Set the path to the shortcut target and add the description.
psl->SetPath(lpszPathObj);
psl->SetDescription(lpszDesc);
// Query IShellLink for the IPersistFile interface, used for saving the
// shortcut in persistent storage.
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
if (SUCCEEDED(hres))
{
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(lpszPathLink, TRUE);
ppf->Release();
}
psl->Release();
}
return hres;
}
void _tmain(int argc, TCHAR *argv[])
{
if (argc > 3)
CreateLink(argv[1], argv[2], argv[3]);
}
Visual Studio generates stdafx.h and stdafx.cpp when you are using new project wizard. If Create empty project checkmark is marked, it will not generate them. These files are used to build a precompiled header file Projname.pch and a precompiled types file Stdafx.obj
For small projects you can eventually remove #include "stdafx.h", but it would be better to create new project with Create empty project unmarked.

GetAppliedGPOList and pGuidExtension value

I'm trying to use the GetAppliedGPOList function, but cannot find/understand what the pGuidExtension should be.
Here's the simple code so far:
#include <Windows.h>
#include <UserEnv.h>
int wmain(int argc, WCHAR *argv[])
{
//GetAppliedGPOList
DWORD flags = GPO_LIST_FLAG_MACHINE;
LPCWSTR machineName = NULL; //Local computer is used
PSID sidUser = NULL;
GUID *pGuidExtension; //What is the GUID of the extension?
PGROUP_POLICY_OBJECT *ppGPOList;
return 0;
}
Cannot run the function because I need to send that value.
Any example about the pGuidExtension value?
I did search here but found nothing about it.
Thank you.
The guids is listed at
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\GPExtensions
For example - Group Policy Client Side Extension List. The GetAppliedGPOList is looked under
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\History\{GuidExtension}
key

Get current user name under Windows

How can I get the current users sign in name in Windows?
What I have figured out is the function
char* user_name;
user_name=getenv("USERNAME");
but the problem is that it gives
admin
but when I sign in to Windows, my user name is "Sudip" and not "admin".
You can use GetUserName
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
You can use GetUserNameEx to get your display name instead of the actual user name. The EXTENDED_NAME_FORMAT enumeration has a NameDisplay entry that should do what you want.

How to give "Everyone" write permissions via C++ MFC on Windows 8?

Im struggling with changing permissions.
I need, on Windows 8, to change the permissions of a file to have group "Everyone" write permissions.
How to I do that?
Im trying to edit a file with C++ MFC which already exists with no "Write" (Everyone) checked, thats causing me many problems.
Your Application need to have the rights to change the permissions for the file.
#pragma comment(lib, "Advapi32.lib")
#include "Aclapi.h"
#include "Sddl.h"
#include <io.h>
#include <sys/stat.h>
void AllowEveryone(CString path)
{
PACL pDacl,pNewDACL;
EXPLICIT_ACCESS ExplicitAccess;
PSECURITY_DESCRIPTOR ppSecurityDescriptor;
PSID psid;
LPTSTR lpStr;
CString str = path;
lpStr = str.GetBuffer();
GetNamedSecurityInfo(lpStr, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION, NULL, NULL, &pDacl, NULL, &ppSecurityDescriptor);
ConvertStringSidToSid("S-1-1-0", &psid);
ExplicitAccess.grfAccessMode = SET_ACCESS;
ExplicitAccess.grfAccessPermissions = GENERIC_ALL;
ExplicitAccess.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ExplicitAccess.Trustee.pMultipleTrustee = NULL;
ExplicitAccess.Trustee.ptstrName = (LPTSTR) psid;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
SetEntriesInAcl(1, &ExplicitAccess, pDacl, &pNewDACL);
SetNamedSecurityInfo(lpStr,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,NULL,NULL,pNewDACL,NULL);
LocalFree(pNewDACL);
LocalFree(psid);
str.ReleaseBuffer();
}

Resources