Using fopen with temp system variable

2020-05-06 22:23发布

I had some doubts about fopen...

Can i perform the following?

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

or do i need to use windows specific functions?

标签: c windows file
2条回答
甜甜的少女心
2楼-- · 2020-05-06 23:03

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

查看更多
\"骚年 ilove
3楼-- · 2020-05-06 23:04

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

查看更多
登录 后发表回答