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

390 Views Asked by At

Background information:

I'm building a file tree in windows using dirent.h (project requirement) on VS2013. I got dirent.h from here. I crash at runtime with a debug assertion failed ("retsize <= sizeInWords") from crt\crtw32\mbstowcs.c, line 283.

To test dirent.h, I used

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 + "  ");
      }
    }
  }
}

which worked (called from main as printDir(".", ""))

so to build my tree I have:

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 = "");

However, calling Dirf(opendir(".")) fails with the debug assertion described above

1

There are 1 best solutions below

0
On

While composing the question, I figured out the answer: I forgot to check for "." and ".." in Dirf's constructor (I remembered to do it in my test case). Adding

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

after dirent* d = readdir(dir) made the error go away.