Skip to content

Instantly share code, notes, and snippets.

@cgwyllie
Created January 16, 2015 00:12
Show Gist options
  • Save cgwyllie/990a83cda7ffb0f32d76 to your computer and use it in GitHub Desktop.
Save cgwyllie/990a83cda7ffb0f32d76 to your computer and use it in GitHub Desktop.
Emscripten scandir implementation
// NOTE implementation created in March 2013, may no longer work with Emscripten master
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/scandir.html
// filter and compar are currently ignored
_scandir = function (dirp, namelist, filter, compar) {
var dirPath = Pointer_stringify(dirp);
var path = FS.analyzePath(dirPath);
var files = [];
if (path.error == 0) {
var file;
for (var name in path.object.contents) {
file = path.object.contents[name];
if (file.isFolder || file.isDevice || !file.read) {
// Skip non-file or unreadable entries
continue;
}
// No filter matching
files.push(name);
}
// No compar support, just lexographic
files.sort();
var pNamelistAlloc = _malloc(4 * files.length);
setValue(namelist, pNamelistAlloc, '*');
var pDirent, nameBytes;
for (var i = 0; i < files.length; i++) {
pDirent = _malloc(268); // sizeof(struct dirent)
pDName = pDirent + 11; // offset of d_name member (32-bit system)
nameBytes = intArrayFromString(files[i]);
for (var j = 0; j < nameBytes.length; j++) {
setValue(pDName + j, nameBytes[j], 'i8');
}
setValue(pNamelistAlloc + (i * 4), pDirent, '*');
}
return files.length;
}
else {
return -1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment