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

标签 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++ 的新手,这可能吗?如果是,怎么办?

最佳答案

您可以使用 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;
}

关于c++ - Ofstream 在 Windows 临时目录中创建一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229477/

相关文章:

c++ - Valgrind 报告 "Invalid free()/delete/delete[]"

windows - 使用 github 操作在 Windows 上测试 Perl

c++ - QProgressBar随着函数的进展而更新

Windows:获取所有*当前*环境变量

c++ - VS Express 2015 Win10 应用程序 - ifstream 无法打开文件

c++ - 为什么早期版本的 C 强制在开始时声明变量?

c++ - 应该翻转数字的程序输出不正确

C++:取消引用 vector<vector<class_ptr*>>

c++ - 使用 ofstream 写入二进制数据时出现问题

c++ - 如何重载 std::ofstream::put()?