Rıdvan Çetin
Rıdvan Çetin

Reputation: 183

Ofstream create a file in Windows temp directory

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

I want to create olustur.bat inside the Windows temp folder. I couldn't manage to achieve it. I am new to C++ so is this possible? If so, how?

Upvotes: 1

Views: 2715

Answers (1)

Raindrop7
Raindrop7

Reputation: 3911

You can use the Win32 API GetTempPath() function to retrieve the full path of the temp folder, then use std::ofstream to write files to it.

#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;
}

Upvotes: 2

Related Questions