"retsize <= sizeInWords" in mbstowcs in dirent.

"retsize <= sizeInWords" in mbstowcs in dirent.h on Windows

本文关键字:quot in mbstowcs dirent lt retsize sizeInWords      更新时间:2023-10-16

>背景信息:

我正在使用VS2013上的dirent.h(项目要求)在窗口中构建文件树。我从这里得到了dirent.h。我在运行时崩溃,调试断言失败("retsize <= sizeInWords"),来自crt\crtw32\mbstowcs.c,第283行。

为了测试dirent.h,我使用了

void printDir(std::string dir, std::string tab)
{
  DIR* d = opendir(dir.c_str());
  dirent* ent = nullptr;
  while (ent = readdir(d)) {
    if (ent->d_name[0] != '.') {
      std::cout << tab << ent->d_name << std::endl;
      if (ent->d_type == DT_DIR) {
        printDir(dir + "/" + ent->d_name, tab + "  ");
      }
    }
  }
}

它有效(从主称为 printDir(".", "))

所以为了建立我的树,我有:

struct Dirf {
  std::string getFullPath() {
    if (out) {
      return out->getFullPath() + "/" + ent.d_name;
    }
    else return ent.d_name;
  }
  Dirf(DIR* dir, Dirf* parent = nullptr)
    : out(parent)
  {
    if (dir) {
      dirent* d = readdir(dir);
      if (d) {
        ent = *d;
        if (dir) {
          next = std::make_shared<Dirf>(dir, parent);
        }
        if (ent.d_type == DT_DIR) {
          DIR* inDir = opendir(getFullPath().c_str());
          in = std::make_shared<Dirf>(inDir, this);
          closedir(inDir);
        }
      }
    }
  }
private:
  typedef std::shared_ptr<Dirf> point;
  friend  std::string to_string(Dirf, std::string);
  dirent ent;
  Dirf* out; // parent to this; in->out == this, out->in == this;
  point in, // in != null iff car.d_type == DT_DIR
        next; // next entry in the dir
};
std::string to_string(Dirf, std::string tab = "");

但是,调用 Dirf(opendir(".")) 失败,并显示上述调试断言

在编写问题时,我想出了答案:我忘了在 Dirf 的构造函数中检查"."和".."(我记得在我的测试用例中这样做)。添加

while (d && d->d_name[0] == '.') { // skip '..' and '.'
    d = readdir(dir);
}

dirent* d = readdir(dir)之后,错误消失了。