<分区>
我最近才接触到 C++,我想做一些简单的事情作为开始。我制作了一个控制台程序,要求用户提供文件路径,然后删除该文件。但是,我遇到了一个我似乎无法解决或找不到解决方案的问题。声明 DeleteFile(filePath.c_str());
给我 2 个错误:
argument of type "const char*" is incompatible with parameter of type "LPCWSTR"
'BOOL DeleteFileW(LPCWSTR)': cannot convert argument 1 from 'const_Elem*' to 'LPCWSTR'
首先,我需要将 std::string
转换为 LPCWSTR
,所以我在最后添加了 c_str()
我发现了这 2 个错误。
我仍然是 C++ 的菜鸟,所以请放轻松。
#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>
int main()
{
loop:
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
std::string filePath;
SetConsoleTextAttribute(h,15);
std::cout << "\nEnter the path of the file you'd like to remove: ";
if (!std::getline(std::cin, filePath)) { std::cout << "I/O error!"; }
while (true)
{
if (!filePath.empty())
{
SetConsoleTextAttribute(h,15);
std::cout << "[+] Checking if file exists";
std::ifstream ifile(filePath);
if (ifile)
{
std::cout << "\n[!] File exists!";
std::cout << "\n[#] Deleting file";
DeleteFile(filePath);
std::ifstream ifile(filePath);
if (!ifile)
{
std::cout << "\n[!] File deleted successfully!";
}
else
{
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
std::cout << "\n[!] Failed to delete file";
}
goto loop;
}
else
{
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
std::cout << "\nPlease enter a valid file path!";
goto loop;
}
break;
}
else
{
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
std::cout << "Please enter a valid file path!";
goto loop;
}
}
std::cout << "\nFile deleted!";
}