c++ - 如何处理无效的异常处理程序例程?
问题描述
我正在构建一个程序,它创建和删除目录。我使用 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 风格进行编程(即使您有 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";
}
然后你尝试删除一个目录四次,显然你不能多次删除一个目录。
等等等等。
推荐阅读
- python - 在这种情况下,切换到警报的命令不起作用
- reactjs - React.cloneElement 克隆已经克隆的元素以添加新的道具
- drake - 将 OMPL 与 Drake 一起使用
- javascript - JS 将数据从“宽”转为“长”
- r - 如何从R中另一个数据框的变量自动制作一个新的数据框?
- php - 如何在for循环中使用uniqid?
- python-3.x - Python3中如何基于unicode码点将汉字写入文件
- php - 在 Bitrix 中,如何在 PHP 中设置列表类型的自定义字段?
- angular - 如何处理打字稿中共享可观察对象中的错误?
- windows - 在 Windows 上运行 Docker 脚本时如何替换“\r”行尾?