C++ 如何修复';文件保留原始位置,复制后不复制扩展名';?
我试图创建一个程序,它在运行到新位置时复制自身,而不保留原始文件位置。一旦它被复制,我就得到了没有扩展名的文件,但是我如何克服这个问题呢C++ 如何修复';文件保留原始位置,复制后不复制扩展名';?,c++,winapi,C++,Winapi,我试图创建一个程序,它在运行到新位置时复制自身,而不保留原始文件位置。一旦它被复制,我就得到了没有扩展名的文件,但是我如何克服这个问题呢 int-tmain(int-argc,_-TCHAR*argv[] { TCHAR szFilepath[MAX_PATH]; TCHAR szFilename[MAX_PATH]; TCHAR szDestpath[MAX_PATH]; /*获取当前可执行文件的完整路径*/ GetModuleFileName(NULL,szFilepath,MAX_PATH
int-tmain(int-argc,_-TCHAR*argv[]
{
TCHAR szFilepath[MAX_PATH];
TCHAR szFilename[MAX_PATH];
TCHAR szDestpath[MAX_PATH];
/*获取当前可执行文件的完整路径*/
GetModuleFileName(NULL,szFilepath,MAX_PATH);
std::wcout根据以下文件:
GetFileTitle
返回系统将用于向用户显示文件名的字符串。仅当用户喜欢显示文件名时,显示名才包含扩展名。这意味着如果在调用文件系统函数时使用返回的字符串,则可能无法准确识别文件离子
您应该使用更合适的函数来获取实际的文件名,例如:
#包括
#包括
#包括
int _tmain(int argc,_TCHAR*argv[]
{
WCHAR szFilepath[MAX_PATH];
LPWSTR-lpszFilename;
WCHAR szDestpath[MAX_PATH];
/*获取当前可执行文件的完整路径*/
getModuleFileName(NULL,szFilepath,MAX_PATH);
std::wcout如果您想要扩展名,那么请不要使用GetFileTitle
,我如何在代码级别执行此操作?@victor_angel27请参阅我的回答谈论文件保留原始位置,我是否应该删除,或者为什么要删除,因为我无法在运行状态下删除?当然,您不能在进程运行时删除原始文件文件仍在运行,已锁定。您必须先退出该进程,然后在另一个进程中执行删除操作(即,在退出之前生成另一个应用程序,并让该应用程序等待原始进程完全退出,然后再删除其文件),或在系统重新启动后(通过MoveFileEx(MOVEFILE\u DELAY\u直到\u重新启动)
)。但这是第二个问题。如果您需要有关该问题的帮助,请将其作为新问题发布。
#include <windows.h>
#include <shlwapi.h>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR szFilepath[MAX_PATH];
LPWSTR lpszFilename;
WCHAR szDestpath[MAX_PATH];
/* Get the current executable's full path */
GetModuleFileNameW(NULL, szFilepath, MAX_PATH);
std::wcout << L"filepath: " << szFilepath << std::endl;
/* Extract just the name */
lpszFilename = PathFindFileNameW(szFilepath);
std::wcout << L"filename: " << lpszFilename << std::endl;
/* Set the destination folder path and file name */
PathCombineW(szDestpath, L"D:\\", lpszFilename);
std::wcout << L"dest path: " << szDestpath << std::endl;
// copys the file of your '.exe'
if (!CopyFileW(szFilepath, szDestpath, FALSE)) {
std::wcout << L"couldnt copy the file";
}
else {
std::wcout << L"copied";
}
return 0;
}
#include <windows.h>
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR szFilepath[MAX_PATH];
std::wstring wFilepath;
std::wstring wFilename;
std::wstring wDestpath;
/* Get the current executable's full path */
wFilepath = std::wstring(szFilepath, GetModuleFileNameW(NULL, szFilepath, MAX_PATH));
std::wcout << L"filepath: " << wFilepath << std::endl;
/* Extract just the name */
wFilename = wFilepath.substr(wFilepath.find_last_of(L"\\/")+1);
std::wcout << L"filename: " << wFilename << std::endl;
/* Set the destination folder path and file name */
wDestpath = L"D:\\" + wFilename;
std::wcout << L"dest path: " << wDestpath << std::endl;
// copys the file of your '.exe'
if (!CopyFileW(wFilepath.c_str(), wDestpath.c_str(), FALSE)) {
std::wcout << L"couldnt copy the file";
}
else {
std::wcout << L"copied";
}
return 0;
}