File: dirent.c

package info (click to toggle)
sameboy 1.0.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 10,528 kB
  • sloc: ansic: 29,948; objc: 22,249; asm: 1,424; pascal: 1,373; makefile: 1,065; xml: 111
file content (51 lines) | stat: -rwxr-xr-x 1,224 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <windows.h>
#include <stdio.h>
#include <winnls.h>
#include <io.h>
#include "dirent.h"

DIR *opendir(const char *filename)
{
    wchar_t w_filename[MAX_PATH + 3] = {0,};
    unsigned length = MultiByteToWideChar(CP_UTF8, 0, filename, -1, w_filename, MAX_PATH);
    if (length) {
        w_filename[length - 1] = L'/';
        w_filename[length] = L'*';
        w_filename[length + 1] = 0;
    }
    DIR *ret = malloc(sizeof(*ret));
    ret->handle = FindFirstFileW(w_filename, &ret->entry);
    if (ret->handle == INVALID_HANDLE_VALUE) {
        free(ret);
        return NULL;
    }
    
    return ret;
}

int closedir(DIR *dir)
{
    if (dir->handle != INVALID_HANDLE_VALUE) {
        FindClose(dir->handle);
    }
    free(dir);
    return 0;
}

struct dirent *readdir(DIR *dir)
{
    if (dir->handle == INVALID_HANDLE_VALUE) {
        return NULL;
    }
    
    WideCharToMultiByte(CP_UTF8, 0, dir->entry.cFileName, -1,
                        dir->out_entry.d_name, sizeof(dir->out_entry.d_name),
                        NULL, NULL);
    
    if (!FindNextFileW(dir->handle, &dir->entry)) {
        FindClose(dir->handle);
        dir->handle = INVALID_HANDLE_VALUE;
    }
    
    return &dir->out_entry;
}