【问题标题】:How to use directory operations in C++Builder?如何在 C++Builder 中使用目录操作?
【发布时间】:2019-01-21 12:27:24
【问题描述】:

我一直在用 C++Builder 创建一个目录。如果您检查此herehere,我会找到适合我的案例的示例,但是当我尝试使用它们时,它们都不适合我!例如,以下代码用于创建目录,其中已经定义了edSourcePath->Text 值。

很遗憾,文档不完整。

try
{
    /* Create directory to specified path */
    TDirectory::CreateDirectory(edSourcePath->Text);
}
catch (...)
{
    /* Catch the possible exceptions */
    MessageDlg("Incorrect path", mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

错误消息显示TDirectory 不是类或命名空间。

另一个问题是,如何通过CreateDirectory(edSourcePath-&gt;Text) 传递源路径和目录名称?

【问题讨论】:

  • 编译器显然找不到TDirectory类的描述,所以它根本不知道TDirectory是什么。由于您使用::,它假定它必须是一个类或命名空间。这就是您收到错误消息的原因。您必须#include 包含它的 .hpp 文件,可能类似于 #include "System.Ioutils.hpp"
  • 所以文档中的源列是我想念的。谢谢。
  • “源码栏”显示的是网页的Wiki格式源码,不是C++源码。不是很有帮助。
  • @RudyVelthuis 文档文本中的“Source”列指定了为正在记录的项目实现 Pascal 源代码的 .pas 文件,以及需要包含在 C++ 中的 .hpp 文件使用该项目的代码。因此,在这种情况下,分别为 System.IOUtils.pasSystem.IOUtils.hpp。也许您正在考虑文档顶部的“查看源代码”选项卡?这是 Wiki 页面源代码。
  • @Remy:现在我很困惑。我在 docwiki 的任何地方都没有看到任何“来源”列。

标签: directory c++builder c++builder-10.2-tokyo


【解决方案1】:

您看到的是编译时错误,而不是运行时错误。编译器找不到TDirectory 类的定义。需要#include定义TDirectory的头文件,例如:

#include <System.IOUtils.hpp> // <-- add this!

try
{
    /* Create directory to specified path */
    TDirectory::CreateDirectory(edSourcePath->Text);

    // or, if either DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE or
    // NO_USING_NAMESPACE_SYSTEM_IOUTILS is defined, you need
    // to use the fully qualified name instead:
    //
    // System::Ioutils::TDirectory::CreateDirectory(edSourcePath->Text);
}
catch (const Exception &e)
{
    /* Catch the possible exceptions */
    MessageDlg("Incorrect path.\n" + e.Message, mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

但是请注意,只有当输入 String 不是有效的格式化路径时,TDirectory::CreateDirectory() 才会引​​发异常。如果实际目录创建失败,它不会抛出异常。事实上,TDirectory::CreateDirectory() 本身无法检测到这种情况,您必须事后检查TDirectory::Exists()

#include <System.IOUtils.hpp>

try
{
    /* Create directory to specified path */
    String path = edSourcePath->Text;
    TDirectory::CreateDirectory(path);
    if (!TDirectory::Exists(path))
        throw Exception("Error creating directory");
}
catch (const Exception &e)
{
    /* Catch the possible exceptions */
    MessageDlg(e.Message, mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

否则,TDirectory::CreateDirectory() 只是 System::Sysutils::ForceDirectories() 的验证包装器,它具有 bool 返回值。因此,您可以直接调用该函数:

#include <System.SysUtils.hpp>

/* Create directory to specified path */
if (!ForceDirectories(edSourcePath->Text)) // or: System::Sysutils::ForceDirectories(...), if needed
{
    MessageDlg("Error creating directory", mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

【讨论】:

猜你喜欢
  • 2018-10-11
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
相关资源
最近更新 更多