如何在%appdata%中创建文件夹,在其中创建.bat文件,然后执行它?

How to create folder in %appdata%, create .bat file in it, and then execute it?

本文关键字:创建 然后 文件 执行 bat 在其中 %appdata% 文件夹      更新时间:2023-10-16

我正在创建C++代码,它将创建一些.bat文件并将其存储在%appdata%文件夹中。我已经成功创建了文件,但仍然无法创建文件夹并执行它。

下面是我的简单代码,它看起来并不简单,但它可以在%appdata%中创建.bat文件,也许有人可以帮助我找到简单的文件。

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#include <direct.h>
int main(int argc, char **argv) {
using namespace std;
std::ofstream aaa;
ostringstream aaa;
aaa.open(aaa1.str());
aaa1 << getenv("appdata") << "/"
<< "test.bat";
aaa.open(aaa1.str());
Updater << "@echo on" << endl;
Updater << "echo "on"" << endl;
return 0;
}

代码在%appdata%中成功创建了.bat文件,但我需要存储在%appdata%的新文件夹中,比如New Folder,然后执行.bat文件。

创建目录 1st使用字符串中的 _dupenv_s() 获取路径添加新文件夹名称"\New Folder">
2nd使用 _mkdir(str.c_str()) 创建目录;3rd使用 std::ofstream outf(str) 创建"test.bat";

#include "stdafx.h"
#include<fstream>
#include<iostream>
#include<conio.h>
#include<direct.h>
using std::cout;
using std::cin;
using std::endl;
int tmain(int argc, TCHAR* argv[])
{
	
	char *pValue;
	size_t len;
	
	
	errno_t err = _dupenv_s(&pValue, &len, "APPDATA");
	std::string NewFile = "\new";
	
	std::string str(pValue);
	str = str + NewFile;
	_mkdir(str.c_str());
	str = str + "\Sample.bat"; //
	std::ofstream outf(str);
	if (!outf)
	{
		printf("error ");
	}
	outf << "this is line1" << endl;
	outf << "line 2" << endl;
	return 0;
}
请!如果有帮助,不要忘记投票

在用户可写位置创建/运行可执行文件是要小心的事情(利用人们运行提升的进程,然后运行攻击有效负载),否则只是将几件事联系在一起。

在Windows上,大多数这些环境变量都是出于旧版/兼容性原因而存在的,SHGetKnownFolderPath是查找文件夹的现代方法。它为路径分配足够的空间,小心使用C-API的手动内存,尽快对其进行unique_ptrwstring。它从Vista工作,如果真的需要,还有较旧的API。

wchar_t *str = nullptr;
SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, NULL, &str); // CHECK RETURN
...use str...
CoTaskMemFree(str);

还要注意文件路径中的 Unicode 和空格。

进程有两个选项,cstdlib标头中有system(command_line),或者对于高级用途,请查看 WindowsCreateProcessW.像这样:

STARTTUPINFO startup;
startup.cb = sizeof(startup);
PROCESS_INFORMATION pi;
CreateProcessW(NULL, L"cmd.exe /C C:\ThePath\myfile.bat", NULL, NULL, FALSE, 0, NULL, NULL, &startup, &pi);

显然特定于Windows。Linux,Mac等都有自己的文件系统布局和安全性。

C++fstream不会自动为您创建目录。您可以将此类目录设置为安装程序的一部分,但是要在运行时执行此操作C++17 具有std::filesystem::create_directories,它采用路径。如果无法使用 C++17,请使用CreateDirectory_mkdir。同样在Windows上要注意Unicode。

相关文章: