#[no_std, cache_output]
// brought to you by camden314
type @file
impl @file {
new: #[desc("Creates a new file IO object") example("@file::new('C:/path/to/file.txt')")](path: @string) {
let ret = {type: @file};
ret.filedata = $.readfile(path);
ret.size = ret.filedata.length;
let ret.fseek = 0;
return ret;
},
seek: #[desc("Sets a position in the file to read from") example("
f = @file::new('data.txt')
f.seek(10)
data = f.read(5) // reads characters 10 to 15
")] (self, s: @number) {
if s < 0 {
throw "Negative seek position " + s as @string;
}
self.fseek = s;
},
read: #[desc("Reads the data in the file from the seek position to the end (or for a specified amount of characters)") example("
data = @file::new('data.txt').read()
")](self, s=-1) {
let size = s
if s == -1 {
size = self.size;
}
if self.fseek >= self.size {
return "";
} else {
oldseek = self.fseek;
self.fseek += size;
return $.substr(self.filedata, oldseek, [self.fseek, self.size].min());
}
}
}