简体   繁体   English

如何使用gcc将homepath导入c程序

[英]How to import homepath into c program using gcc

I am using gcc for windows .我在windows 上使用gcc The OS is windows XP .操作系统是Windows XP How do I import the homepath variable into my c program so I can write to c:\\%homepath%\\desktop?如何将 homepath 变量导入到我的 c 程序中,以便我可以写入 c:\\%homepath%\\desktop? I would like to use something similar to:我想使用类似的东西:

fd = fopen("C:\\\\%%homepath%%\\\\desktop\\\\helloworld.txt","w") ; fd = fopen("C:\\\\%%homepath%%\\\\desktop\\\\helloworld.txt","w") ;

使用 getenv() 获取环境变量的值,然后使用 sprintf 或 strcat 组成路径。

Use getenv("homepath") to get the value of environment variable.使用getenv("homepath")获取环境变量的值。 You should handle the case in which the variable has not been defined ( getenv returns NULL in that case).您应该处理尚未定义变量的情况(在这种情况下getenv返回NULL )。

To compose the path use sprintf使用sprintf路径

char * homepath = getenv("homepath");

if(homepath == null) {
    /* variable HOMEPATH has not been defined */ 
}

sprintf(path,"%s\\desktop\\helloworld.txt",homepath);

You should make path big enough to accomodate the value homepath and \\\\desktop\\\\helloworld.txt .您应该使路径足够大以容纳值homepath\\\\desktop\\\\helloworld.txt

Also note the use of \\\\ in the string.还要注意字符串中\\\\的使用。 You can't use single \\ .您不能使用单个\\

Note: you actually need to get the value of HOMEDRIVE as well, and prepend that to HOMEPATH.注意:您实际上还需要获取 HOMEDRIVE 的值,并将其添加到 HOMEPATH。 In many corporate environments, the home directories are kept on large network appliances or servers.在许多公司环境中,主目录保存在大型网络设备或服务器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM