首页 > 解决方案 > 如何处理无效的异常处理程序例程?

问题描述

我正在构建一个程序,它创建和删除目录。我使用 MSVC 编译器(Visual Studio 2017),这就是我不能分别使用“getcwd()”或“dirent.h”的原因。我尝试了几种不同的方法来获取当前的工作目录,但总是有问题。我设法用“_wgetcwd()”打印了 cwd。但是,在我的研究中,我找不到如何转换它的输出以在“_rmdir()”或“_wrmdir()”中使用它。

我的主要目标是能够删除目录而无需安装一些新的编译器。如果满足这个条件,任何帮助表示赞赏,因为我已经尝试安装不同的编译器,但我没有让它工作。我还尝试了不同的方法来获取 cwd 并将其转换为所需的数据类型,但在我的 IDE 范围和我的基本知识范围内没有任何效果。

我几乎是编程的初学者,我正在学习这本书,不幸的是使用了“dirent.h”。以下是我当前代码的片段,其中我已经消除了所有错误。但是我仍然得到最后一个烦人的异常:

#include <iostream>
#include <stdlib.h>
#include<string>
#include <direct.h>

int main() {

    int t = 0;
    std::string str;
    char xy = ' ';
    char* _DstBuf = &xy;
    const char* uniquename;
    uniquename = _getdcwd(0, _DstBuf, _MAX_PATH);
    std::cout << "Current path is ";    
    while (*uniquename != '\0') // this pointer points to the beginning of my path
    {
        std::cout << char(*uniquename); //  prints one char of the path name for each iteration

        char var = char(*uniquename);

        str.push_back(var); //here the exception below is thrown.

        // jump to the next block of memory
        uniquename++;
    }
    std::cout << str <<'\n';

    const char* lastchance = str.c_str();

    if (_wchdir('..')) {
        std::cout << "changing directory failed.\n";
    }

    if (_rmdir(lastchance) == -1 && errno == ENOTEMPTY) { 
        std::cout << "Given path is not a directory, the directory is not empty, or the directory is either the current working directory or the root directory.\n";
    }
    else if (_rmdir(lastchance) == -1 && errno == ENOENT) 
    {
        std::cout << "Path is invalid.\n";
    }
    else if (_rmdir(lastchance) == -1 && errno == EACCES)
    {
        std::cout << "A program has an open handle to the directory.\n";
    }
    else if (_rmdir(lastchance)) {
        std::cout << "removing directory still not possible\n";
    }

}

这是我得到的异常: Experimentfile.exe 中 0x6E656D69 处的未处理异常:0xC00001A5:检测到无效异常处理程序例程(参数:0x00000003)。

标签: c++exceptionvisual-c++

解决方案


因此,如果您打算以 C 风格进行编程(即使您有 C++ 编译器),您将不得不学习数组和指针的工作原理。从互联网上学习的话题太大了,您需要一本好书

但是我会指出一些错误

char xy = ' ';
char* _DstBuf = &xy;
const char* uniquename;
uniquename = _getdcwd(0, _DstBuf, _MAX_PATH);

这简直是​​大错特错。它可以编译,但这并不意味着它会起作用。这是需要的

char DstBuf[_MAX_PATH];
_getdcwd(0, DstBuf, _MAX_PATH);

_getdcwd 需要一个作为指针传递的数组(请参阅,您需要了解数组和指针)。

然后您尝试打印出结果并将结果分配给一个字符串。同样,代码比它需要的复杂得多。这是更简单的版本

std::string str = DstBuf;
std::cout << str <<'\n';

然后您尝试更改目录。我不知道为什么_wchdir当您有窄字符串时使用宽版本,请_chdir改用。再次参数不正确,'..'是一个多字符文字,但_chdir需要一个 C 字符串。这是使用的正确版本_chdir

if (_chdir("..")) {
    std::cout << "changing directory failed.\n";
} 

然后你尝试删除一个目录四次,显然你不能多次删除一个目录。

等等等等。


推荐阅读