首页 > 解决方案 > C语言中如何修改环境变量

问题描述

我正在开发我的游戏并决定使用 eclipse 作为我的编译器。我必须为两个平台编译它:x86 和 x64。麻烦从那里开始。系统路径中有很多依赖文件。每次我都必须更改它们才能更改平台。因此,我创建了一条线来更快地设置我的配置并且不影响路径本身。这是添加到我创建的路径中的行:%DRIVE%\mingw\mingw%PLATFORM%\bin;%DRIVE%\Dropbox\Machine\Windows\C\Place\bin\x%PLATFORM%;%驱动器%\Dropbox\Machine\Windows\C\PLUGIN\x%PLATFORM%\bin;

正如你们所看到的,那里有两个变量:%DRIVE% 和 %PLATFORM%。我希望用我尝试在 c 中创建的文件来更改它们。

这是代码

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

char *strremove(char *str, const char *sub) {
    char *p, *q, *r;
    if ((q = r = strstr(str, sub)) != NULL) {
        size_t len = strlen(sub);
        while ((r = strstr(p = r + len, sub)) != NULL) {
            while (p < r)
                *q++ = *p++;
        }
        while ((*q++ = *p++) != '\0')
            continue;
    }
    return str;
}

#ifndef HAVE_SETENV
int setenv(const char * variable,const char * value) {
    if(!variable || !value)return(0);
    int len = strlen(variable)+1+strlen(value)+1;
    char * EnvString = calloc(len,sizeof(char));
    sprintf(EnvString, "%s=%s", variable, value);
    if (!_putenv(EnvString)) {
        return (1);
    }
    if(EnvString)free(EnvString);
    return (0);
}
#endif

void change_platform(int argc,char ** argv) {
    char * variable = "PLATFORM",* value = "86";
    if(argc > 1){
        value = argv[1];
    }
    if (setenv(variable, value)) {
        printf("\n environmental variable successfully written");
        printf("\n value of the environmental variable written is %s",
                getenv(variable));

    } else {
        printf("\n error in writing the environmental variable");
    }
}

int main(int argc, char ** argv) {
    change_platform(argc,argv);
    getch();
    return 0;
}

我的代码在程序中显示了正确的结果,但是当我去检查系统环境本身时,没有任何变化。难道我做错了什么。详细信息:我认为这是因为 mingw 不是 Windows 原生的,然后我也在 Visual c++ 中创建了 I 文件,但它也不起作用。

标签: cwindowsenvironment-variables

解决方案


请记住它只影响当前进程的环境

获取环境,_wgetenv

int main( void )
{
   char *libvar;

   // Get the value of the LIB environment variable.
   libvar = getenv( "LIB" ); // C4996
   // Note: getenv is deprecated; consider using getenv_s instead

   if( libvar != NULL )
      printf( "Original LIB variable is: %s\n", libvar );

   // Attempt to change path. Note that this only affects the environment
   // variable of the current process. The command processor's
   // environment is not changed.
   _putenv( "LIB=c:\\mylib;c:\\yourlib" ); // C4996
   // Note: _putenv is deprecated; consider using putenv_s instead

   // Get new value.
   libvar = getenv( "LIB" ); // C4996

   if( libvar != NULL )
      printf( "New LIB variable is: %s\n", libvar );
}

推荐阅读