为什么我不能将 Windows 环境路径与 ofstream 一起使用来编写文本文件?

Why i can't use Windows Environment path with ofstream to write a text file?

本文关键字:文件 文本 一起 ofstream 不能 Windows 环境 路径 为什么      更新时间:2023-10-16

为什么我不能将Windows环境路径快捷方式与ofstream一起使用来编写示例文本文件?

\ C:UsersMeAppDataLocalTempTest.txt
std::string Path = "%Temp%\Test.txt"
ofstream myfile;
myfile.open (Path);
if (!myfile.is_open())
{
cout << "Could not create temp file." << endl;
}
myfile << "Hello World";
myfile.close();

myfile.is_open((总是返回 false,"%%Temp%%"和 "\%Temp\%" 不起作用。

我可以通过Windows API获取临时路径,但我不想在此应用程序中使用API。

谢谢

%Temp%替换是由某些Windows程序完成的,而不是由C++运行时完成的。如果要执行此操作,只需自己检索环境变量并构建路径即可。像这样的事情可以做到这一点,但您需要添加一些错误检查:

ostringstream tempfilepath;
tempfilepath << getenv("Temp") << '/' << "Test.txt";
ostream myFile;
myFile.open(tempfilepath.str());
...etc...