Using fopen with temp system variable

后端 未结 2 872
自闭症患者
自闭症患者 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 12:50

    On Windows you can use GetTempPath function that simply expands your %TEMP% env variable.

    Note, that starting from C++17 you can use std::filesystem::temp_directory_path

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题