c - 将 fopen 与 temp 系统变量一起使用

标签 c windows file

我对fopen有一些疑问...

我可以执行以下操作吗?

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

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

最佳答案

不,您不能直接执行此操作(除非您想打开名为 %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");

但是您的情况有一个更清洁选项 - tmpfile

关于c - 将 fopen 与 temp 系统变量一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705490/

相关文章:

c - Windows 上 C 中的目录列表

c - 是否可以在 MS Windows 上编译 C89 代码?

在 c 中为 Windows 操作系统创建中断

java - Java如何只读取每一行的第二个单词

c - C 中带有比较 SSE 的 If 语句

c - 无法在 C 循环外释放指针?

php - 从文件中读取第一行的最快方法

macos - 如何使用 SSH 和 MAC OS X 终端在计算机之间复制文件

Makefile 教程中令人困惑的 Sed 单行代码

ruby-on-rails - 从 Windows 访问在 Vagrant box 上运行的 Rails 服务器