int main() { // Criar arquivos na raiz FILE2 files[4]; files[0] = create2("/hello.txt"); printf("Testing double dot.\n"); files[1] = create2("../helloDD.txt"); files[2] = create2("/../../helloDD2.txt"); files[3] = create2("./helloD.txt"); DIRENT2 dentry; DIR2 d = opendir2("/"); while (readdir2(d, &dentry) == 0) { printf("Entry: Name => %s, Type => %s, Size => %lu.\n", dentry.name, (dentry.fileType == 0x01 ? "File" : "Directory"), dentry.fileSize); } int i; for (i = 0; i < 4; ++i) close2(files[i]); return 0; }
void cmdLs(void) { // Pede o nome do diretorio de trabalho char cwd[1024]; int err = getcwd2(cwd, 1024); if (err) { printf ("Working directory not found\n"); return; } // Abre o diretório de trabalho DIR2 d; d = opendir2(cwd); if (d<0) { printf ("Open dir error: %d\n", err); return; } // Coloca diretorio na tela DIRENT2 dentry; while ( readdir2(d, &dentry) == 0 ) { printf ("%c %8ld %s\n", (dentry.fileType?'d':'-'), dentry.fileSize, dentry.name); } closedir2(d); }
/* * The scandir() function reads the directory dirname and builds an * array of pointers to directory entries using malloc(3). It returns * the number of entries in the array. A pointer to the array of * directory entries is stored in the location referenced by namelist. * * The select parameter is a pointer to a user supplied subroutine * which is called by scandir() to select which entries are to be * included in the array. The select routine is passed a pointer to * a directory entry and should return a non-zero value if the * directory entry is to be included in the array. If select is null, * then all the directory entries will be included. * * The compar parameter is a pointer to a user supplied subroutine * which is passed to qsort(3) to sort the completed array. If this * pointer is null, the array is not sorted. */ int scandir(const char *dirname, struct dirent2 ***ret_namelist, int (*select)(const struct dirent2 *), int (*compar)(const struct dirent2 **, const struct dirent2 **)) { int i, len; int used, allocated; DIR2 *dir; struct dirent2 *ent, *ent2; struct dirent2 **namelist = NULL; if ((dir = opendir2(dirname)) == NULL) return -1; used = 0; allocated = 2; namelist = malloc(allocated * sizeof(struct dirent2 *)); if (!namelist) goto error; while ((ent = readdir2(dir)) != NULL) { if (select != NULL && !select(ent)) continue; /* duplicate struct direct for this entry */ len = offsetof(struct dirent2, d_name) + strlen(ent->d_name) + 1; if ((ent2 = malloc(len)) == NULL) return -1; if (used >= allocated) { allocated *= 2; namelist = realloc(namelist, allocated * sizeof(struct dirent2 *)); if (!namelist) goto error; } memcpy(ent2, ent, len); namelist[used++] = ent2; } closedir2(dir); if (compar) qsort(namelist, used, sizeof(struct dirent2 *), (int (*)(const void *, const void *)) compar); *ret_namelist = namelist; return used; error: if (namelist) { for (i = 0; i < used; i++) free(namelist[i]); free(namelist); } return -1; }