tov / dssl2

A data structures student language, version 2
MIT License
9 stars 4 forks source link

Add file I/O #7

Closed nat82alie closed 5 years ago

nat82alie commented 5 years ago

This PR implements the functionality to read from and write to files in both text and binary mode. This makes it easier for students to test their data structures on big data. I have also included unit tests for all modes.

Writing in text mode would look like:

> let f0 = open('in.txt', 'w', 't')
> f0.write("hello\n\nmy name is\n")  # writes to file, returns number of characters written
17
> f0.write("nat")
3
> f0.close()

Reading in text mode would look like:

> let f1 = open('in.txt', 'r', 't')
> f1.readline()  # reads a line from the file
"hello"
> f1.readchar()  # reads single character from file
"\n"
> f1.readline()
"my name is"
> f1.readchar()
"n"
> f1.readchar()
"a"
> f1.readchar()
"t"
> f1.readchar()
#<EOF>
> f1.readline()
#<EOF>
> f1.close()

Writing in binary mode would look like:

> let f2 = open('in.txt', 'w', 'b')
> f2.write([255, 97, 98, 34])  # accepts a vector of decimal ascii values, writes to file, returns number of bytes written
4
> f2.write([2, 0,  10, 19, 95, 131])
6
> f2.close()

Reading in binary mode would look like:

> let f3 = open('in.txt', 'r', 'b')
> f3.readbyte()  # reads single byte from file
255
> f3.readbyte()
97
> f3.readline()  # reads a line from the file, until \r (ascii 13) or \n (ascii 10), returns vector of decimal ascii values
[98, 34, 2, 0]
> f3.readline()
[19, 95, 131]
> f3.readline()
#<EOF>
> f3.readbyte()
#<EOF>
> f3.close()
tov commented 5 years ago

Thanks for the PR! I would indeed like this feature, and I’m considering both this design and a few others.