I just recently got into C++, and I wanted to make something simple to start off with. I made a console program that asks the user for a file path and then deletes the file. However, I've encountered a problem I cannot seem to resolve or find a solution for. The statement DeleteFile(filePath.c_str());
is giving me 2 errors:
argument of type "const char*" is incompatible with parameter of type "LPCWSTR"
'BOOL DeleteFileW(LPCWSTR)': cannot convert argument 1 from 'const_Elem*' to 'LPCWSTR'
First of all, I need to convert std::string
to LPCWSTR
, so I added c_str()
in the end which gave me those 2 errors.
I'm still a noob in C++ so go easy on me.
#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!";
}