Using fopen with temp system variable

后端 未结 2 871
自闭症患者
自闭症患者 2021-01-28 12:45

I had some doubts about fopen...

Can i perform the following?

fopen(\"%temp%\" , \"r\");

or do i need to use windows specific functions

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-28 13:16

    No, you cannot do directly (unless you want to open file called %temp). There is a function ExpandEnvironmentStrings that does that:

    char path[MAX_PATH];
    ExpandEnvironmentStrings("%TEMP%\\tempfile", path, MAX_PATH);
    fopen(path, "r");
    

    You can do that manually -- in this case it can be more portable:

    char path[MAX_PATH];
    const char* temp = getenv("TEMP");
    
    if(temp == NULL)
        ; // Return an error or try to guess user's Temp 
          // directory with GetUserProfileDirectory or similiar functions
    
    snprintf(path, MAX_PATH - 1, "%s\\tempfile", temp);
    
    fopen(path , "r");
    

    But there is a cleaner option for your case -- tmpfile

提交回复
热议问题