【问题标题】:Using fopen with temp system variable将 fopen 与 temp 系统变量一起使用
【发布时间】:2015-06-29 23:56:53
【问题描述】:

我对fopen有些疑惑……

我可以执行以下操作吗?

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

或者我需要使用 Windows 特定的功能吗?

【问题讨论】:

  • "%temp%" 是否为您提供文件名,以及请求操作所需的权限?
  • 我不明白你的问题,你能改写吗?
  • fopen("%temp%" , "r") 将尝试打开一个名为...的文件...好吧.. %temp%。

标签: c windows file


【解决方案1】:

在 Windows 上,您可以使用 GetTempPath 函数来简单地扩展您的 %TEMP% 环境变量。

注意,从 C++17 开始,您可以使用 std::filesystem::temp_directory_path

【讨论】:

    【解决方案2】:

    不,您不能直接执行(除非您要打开名为 %temp 的文件)。有一个函数ExpandEnvironmentStrings 可以做到这一点:

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

    您可以手动执行此操作——在这种情况下,它可以更便携:

    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");
    

    但是对于您的情况,有一个 cleaner 选项 -- tmpfile

    【讨论】:

    • temp = "C:\\Windows\\Temp"; 现在已经不行了。它曾经在 Windows 95/98 下工作,但从 Windows 2000 开始,您不能简单地写入 C:\Windows 目录。
    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 2011-09-16
    • 1970-01-01
    • 2021-07-06
    • 2016-07-29
    • 2014-02-20
    • 2016-07-01
    • 1970-01-01
    相关资源
    最近更新 更多