cmc/learn
My personal learning area.
clone: git clone https://gitbay.org/cmc/learn.git
main: hare/files/files.ha · raw
1use bufio;
2use fmt;
3use fs;
4use io;
5use os;
6use strings;
7
8export fn main() void = {
9 // Get user input
10 const filename = get_filename();
11 const filedata = get_input();
12
13 // Save to file and return the message
14 let message = save_input(filename, filedata);
15 fmt::printfln("{}", message)!;
16};
17
18fn get_filename() str = {
19 // Ask user for filename
20 fmt::printfln("Enter a file name to create:")!;
21
22 // Read the buffer
23 const input = bufio::scanline(os::stdin)! as []u8;
24
25 // Convert to string and return
26 return strings::fromutf8(input)!;
27};
28
29fn get_input() []u8 = {
30 // Ask user for input
31 fmt::printfln("Enter some words or data to write to a file:")!;
32
33 // Read the buffer
34 const input = bufio::scanline(os::stdin)! as []u8;
35
36 // Return the data
37 return input;
38};
39
40fn save_input(file_name: str, file_data: []u8) str = {
41 // USER_RW = 384, Read and write permissions for the file owner
42 let file_mode: fs::mode = 384;
43
44 // Create a file buffer as USER_RW using the provided file name
45 let file_buffer = os::create(file_name, file_mode);
46
47 // Handle the tagged union for (1) a successful file buffer, or (2) an
48 // error
49 match (file_buffer) {
50 // (1) Write the data, close the file, and return a success message
51 case let file: io::file =>
52 io::write(file, file_data)!;
53 io::close(file)!;
54 return "Data saved successfully. Check the file you created!";
55 // (2) Return the error message as a string
56 case let e: fs::error =>
57 return fs::strerror(e);
58 };
59};
60