Text Files
Text files are very common and easy to create. They can be used to store results, configurations or data.
Read
Reading a text file requires using a TextReader. It is instantiated using the path to the file to read. Once opened, the reader provides information on the quantity of bytes to read with available():int, and the current position of the reader in the file get_pos(): int to be able to follow the progress.
fn run() {
var filePath: String = "./myTextFile.txt";
var reader = TextReader::new(filePath);
if(reader == null) {
throw "Could not open file at ${filePath}";
}
while(reader.available() > 0) {
var line = reader.readLine();
println("Progress: ${reader.get_pos()/reader.available()*100}%");
}
}
If you want to skip a portion of the file you have already processed, you can set the position of the cursor of the reader to a specific place using set_pos(pos: int).
Write
Writing text works in the same idea. When creating a TextWriter, you can choose between overriding or appending to an existing file.
To this end you can use the new(path: String): TextWriter function, to create or override a file, or new_append(path: String): TextWriter to create or append to a file.
Once the writer created, you can use three functions to write
fn run() {
var filePath: String = "./myTextFile.txt";
var writer = TextWriter::new(filePath);
if(writer == null) {
throw "Could not open file at ${filePath}";
}
writer.write("This is the beginning of the line.");
writer.writeln(" This is the end of the line.");
}
As for other file IO types, set_pos(), get_pos() allows to position the current location in the file. This can be useful to recover from any interruption while reading the file. If this position is stored in the data store (persisted), then this recovery mechanism survives GreyCat restarts.