【问题标题】:Ofstream create a file in Windows temp directoryOfstream 在 Windows 临时目录中创建一个文件
【发布时间】:2017-03-06 21:12:21
【问题描述】:
ofstream batch;
batch.open("olustur.bat", ios::out);
batch <<"@echo off\n";
batch.close();
system("olustur.bat");

我想在 Windows 临时文件夹中创建 olustur.bat。我无法实现它。我是 C++ 新手,这可能吗?如果有,怎么做?

【问题讨论】:

  • 通常在C:\users\&lt;username&gt;\AppData\Local\Temp
  • 是的,但这仅适用于我的电脑。
  • Temp 也存储在%TEMP% 中。根据您编译 C++ 的方式,您可以使用 std::getenvGetEnvironmentVariable
  • %TEMP%\olustur.bat 也不起作用
  • 您不能直接将%TEMP%ofstream 一起使用(或任何其他文件I/O 函数,就此而言)。你必须先查询它的值。使用std::getenv("TEMP")GetEnvironmentVariable("TEMP") 获取解析的临时路径,然后将您的文件名附加到该路径的末尾,然后将该完整路径传递给ofstream。 .

标签: c++ windows ofstream temp


【解决方案1】:

您可以使用 Win32 API GetTempPath() 函数检索临时文件夹的完整路径,然后使用 std::ofstream 向其中写入文件。

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    CHAR czTempPath[MAX_PATH] = {0};
    GetTempPathA(MAX_PATH, czTempPath); // retrieving temp path
    cout << czTempPath << endl;

    string sPath = czTempPath;
    sPath += "olustur.bat"; // adding my file.bat

    ofstream batch;
    batch.open(sPath.c_str());
    batch << "@echo off\n";
    batch.close();

    system(sPath.c_str());

    return 0;
}

【讨论】:

  • 其实我的问题是把它放到这里 'batch.open("olustur.bat", ios::out);'
  • @RıdvanÇetin 听起来你需要了解如何连接字符串。
猜你喜欢
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-04
  • 1970-01-01
  • 2012-02-03
  • 2013-09-18
相关资源
最近更新 更多