Ofstream在Windows临时目录中创建一个文件

时间:2016-10-25 00:14:40

标签: c++ windows ofstream temp

ofstream batch;
batch.open("olustur.bat", ios::out);
batch <<"@echo off\n";
batch.close();
system("olustur.bat");

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

1 个答案:

答案 0 :(得分:2)

您可以使用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;
}
相关问题