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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
#pragma once
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include "typedef.h"
#include "allocator.h"
inline void* file_read( const char* file, U64* size = nullptr ) {
FILE* f = fopen( file, "rb" );
if( !f )
return 0;
defer( fclose( f ) );
fseek( f, 0, SEEK_END );
U64 fsize = ftell( f );
rewind( f );
if( !fsize )
return 0;
void* block = malloc( fsize + 1 );
fread( block, fsize, 1, f );
( (U8*)block )[fsize] = 0;
if ( size ) *size = fsize;
return block;
}
inline void file_write( const char* file, U8* data, U32 size ) {
FILE* f = fopen( file, "wb" );
if( !f )
return;
fwrite( data, size, 1, f );
fclose( f );
}
inline const char* file_path_last_of( const char* path ) {
const char* last_slash = strrchr( path, '/' );
return last_slash? last_slash + 1 : path;
}
struct FILE_ENTRY {
char name[256];
U8 dir;
};
inline LIST<FILE_ENTRY> dir_get_entries( const char* path ) {
LIST<FILE_ENTRY> entries;
DIR* dir = opendir( path );
if( !dir )
return entries;
struct dirent* entry;
struct stat file_stat;
char full_path[512];
while( !!( entry = readdir( dir ) ) ) {
if( !strcmp( entry->d_name, "." ) || !strcmp( entry->d_name, ".." ) )
continue;
snprintf( full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if( stat( full_path, &file_stat ) )
continue;
FILE_ENTRY file_entry;
strncpy( file_entry.name, entry->d_name, sizeof(file_entry.name) - 1 );
file_entry.name[sizeof(file_entry.name) - 1] = '\0';
file_entry.dir = S_ISDIR( file_stat.st_mode ) ? 1 : 0;
entries.push( file_entry );
}
closedir( dir );
return entries;
}
|