我正在构建一个程序,用于创建和删除目录。我使用 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++ 编译器),您将必须学习数组和指针的工作原理。从互联网上学习这个话题远太大了,你需要good book .
但是我会指出一些错误
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
。再次,参数不正确,'..'
是多字 rune 字,但 _chdir
需要 C 字符串。这是使用 _chdir
的正确版本。
if (_chdir("..")) {
std::cout << "changing directory failed.\n";
}
然后你尝试删除一个目录四次,显然你不能删除一个目录超过一次。
等等,等等。
关于c++ - 我如何处理无效的异常处理例程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61190919/