dir_info

Code

main.odin ¶
77 linesSource

1/*
2How to get information about a directory, including which files and directories
3it contains.
4*/
5package dir_info
6
7import "core:fmt"
8import "core:os"
9
10main :: proc() {
11	cwd, wd_err := os.get_working_directory(context.allocator)
12	if wd_err != nil {
13		fmt.eprintfln("Could not get working directory: %v", wd_err)
14		os.exit(1)
15	}
16	defer delete(cwd)
17
18	// Swap `cwd` for some other string to change which folder you're looking at
19	f, open_err := os.open(cwd)
20	if open_err != nil {
21		fmt.eprintfln("Could not open directory for reading: %v", open_err)
22		os.exit(1)
23	}
24	defer os.close(f)
25
26	/*
27	File_Info :: struct {
28		fullpath:          string,        // fullpath of the file
29		name:              string,        // base name of the file
30
31		inode:             u128,          // might be zero if cannot be determined
32		size:              i64 `fmt:"M"`, // length in bytes for regular files; system-dependent for other file types
33		mode:              Permissions,   // file permission flags
34		type:              File_Type,
35
36		creation_time:     time.Time,
37		modification_time: time.Time,
38		access_time:       time.Time,
39	}
40
41	(from <odin>/core/os/stat.odin)
42	*/
43	fis: []os.File_Info
44
45	/*
46	This will deallocate `fis` at the end of this scope.
47
48	It's not allocated yet, but `fis` is assigned a return value from
49	`os.read_dir`. That's a	dynamically allocated slice.
50	
51	It doesn't matter that `fis` hasn't been assigned yet: `defer` will fetch
52	the variable `fis` at the end of this scope. It does not fetch the value of
53	that variable now.
54
55	Note that each `File_Info` contains an allocated `fullpath` field. That's
56	why this uses `os.file_info_slice_delete(fis)` instead of `delete(fis)`:
57	It needs to go through the slice and deallocate those strings.
58	*/
59	defer os.file_info_slice_delete(fis, context.allocator)
60
61	read_err: os.Error
62	fis, read_err = os.read_dir(f, -1, context.allocator) // -1 reads all file infos
63	if read_err != nil {
64		fmt.eprintfln("Could not read directory: %v", read_err)
65		os.exit(2)
66	}
67
68	fmt.printfln("Current working directory %v contains:", cwd)
69
70	for fi in fis {
71		if fi.type == .Directory {
72			fmt.printfln("%v (directory)", fi.name)
73		} else {
74			fmt.printfln("%v (%M)", fi.name, fi.size)
75		}
76	}
77}

Declarations Used 10