gpt4 book ai didi

C++创建后无法打开文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:41 25 4
gpt4 key购买 nike

我正在尝试制作一个程序,然后使用此代码打开它。

//Make the file
std::ifstream src(a, std::ios::binary);
std::ofstream dst(b, std::ios::binary);

dst << src.rdbuf();

//Execute it
Execute((LPCTSTR)b.c_str());

函数执行:

bool Execute(LPCTSTR Process)
{
STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;

ZeroMemory(&sInfo, sizeof(sInfo));

sInfo.cb = sizeof(sInfo);

ZeroMemory(&pInfo, sizeof(pInfo));

if (!CreateProcess(Process, "open", NULL, NULL, false, 0, NULL, NULL, &sInfo, &pInfo))
{
return 0;
}

return 1;
}

我已经测试过制作文件,当我手动打开文件时它可以正常工作,没有任何问题。我尝试了执行功能,它工作正常,不是一个问题。但是当我出于某种原因将这两个组合在一起时,它不会执行。

如果有人能告诉我为什么和/或如何解决它,那将非常有帮助。

谢谢。

最佳答案

不妨输入完整答案。基本上,如果 ofstream 没有关闭,createProcess 就会失败。这是要测试的示例代码:

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

bool Execute(LPCTSTR Process)
{
STARTUPINFO sInfo = {};
sInfo.cb = sizeof(sInfo);
PROCESS_INFORMATION pInfo = {};

return CreateProcess(Process, NULL, NULL, NULL, FALSE, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &sInfo, &pInfo);
}

int main()
{
std::wstring src_name(L"C:\\Windows\\system32\\notepad.exe");
std::wstring dst_name(L"C:\\Users\\KK\\Desktop\\mynotepad.exe");

std::ifstream src(src_name, std::ios::binary);
std::ofstream dst(dst_name, std::ios::binary);

dst << src.rdbuf();

src.close();
dst.close(); // has to be closed before execution

if (!Execute(dst_name.c_str()))
{
std::cout << "ERROR: " << GetLastError() << std::endl;
}

return 0;
}

注释掉 dst.close(); 会产生错误。

关于C++创建后无法打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com