简体   繁体   中英

How to import homepath into c program using gcc

I am using gcc for windows . The OS is windows XP . How do I import the homepath variable into my c program so I can write to c:\\%homepath%\\desktop? I would like to use something similar to:

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

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

Use getenv("homepath") to get the value of environment variable. You should handle the case in which the variable has not been defined ( getenv returns NULL in that case).

To compose the path use 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 .

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. In many corporate environments, the home directories are kept on large network appliances or servers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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