c++ - C++删除文件

标签 c++ winapi

<分区>

我最近才接触到 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!";
}

最佳答案

您混合使用了 native Windows 和标准 C 风格的系统调用,这是问题的一部分。 C 函数通常采用 const char* 指针,而 native Windows 调用使用 16 位字符(尽管您可以为您的编译器切换它)。

您可以使用常规的 C remove() 调用来删除文件,或者使用 DeleteFileA Windows 调用,它需要 8 位字符。

正确地将字符串从 8 位转换为 16 位可能比您在此阶段需要的更令人头疼...

https://en.cppreference.com/w/c/io/remove

https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-deletefilea

关于c++ - C++删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59030872/

相关文章:

c# - SendMessage 消失在以太中

c++ - 使用Qt将所有数据库操作放在一个特定的线程中

java - 将负图像转换为正图像

c# - 将 SetTimer() 和 KillTimer() 移植到 C#?

c++ - 将文本/图像写入 HWND 的最短代码是什么

c++ - winapi mouse_event 错误坐标

delphi - 如何在打开对话框中设置排序模式

c++ - 逐字比较字符串 C++

c++ - 如何从 C++ 程序执行 C# exe

c++ - 如何调用 clang++ 或 g++ 来准确复制两个不同标准版本中的需求