dan200 / ComputerCraft

Programmable Computers for Minecraft
Other
982 stars 198 forks source link

[Suggestion] fs API is highly limited #504

Open ghost opened 6 years ago

ghost commented 6 years ago

The fs API is very limited due to its lack of an ability to read characters except as numbers (in which case neither lines nor the entire file can be read). I suggest adding the following function in text mode:

h.readChars(number size): Reads size characters from the open file h and return them as a string.

Also, there is no ability to "seek" backwards in a file. I'd recommend adding something like the standard io API's file:seek().

ghost commented 6 years ago

This obviously has to be done in the Java layer, but without it the only option for reading arbitrary-length strings and seeking backwards is to either readAll() into a buffer and work with that or use read() to get single bytes and deal with the string<->number conversions and reopening the file to go back to the start.

SquidDev commented 6 years ago

h.readChars(number size) Reads size characters from the open file h and return them as a string.

This should have been implemented as of #238. One can do h.read(123) to read 123 characters.

Also, there is no ability to "seek" backwards in a file. I'd recommend adding something like the standard io API's file:seek().

This is something I'd really like to see as well. The current IMount/IWritableMount infrastructure doesn't handle it as they work with InputStream/OutputStreams. It might be possible to switch to ReadableByteChannel and WritableByteChannels instead, adding seek support if the returned channel implements SeekableByteChannel. Obviously this'd be a breaking change and so we'd have to wait for 1.13.

ghost commented 6 years ago

Ah, didn't see 238. Thanks for responding.

EDIT: Nitpick: Technically, h.read(123) would read 123 bytes, which is not necessarily the same as 123 characters. Unicode allows multibyte characters; in the case of UTF-16 (Windows) or UTF-32 (some internal implementations), all characters are multibyte.

JasonTheKitten commented 6 years ago

Backwards file seeking would probably be possible with a buffer on the lua side?

SquidDev commented 6 years ago

Yeeees, but then you might as well just read the entire file and then use string.sub. Seeking is useful when you don't want to load the whole file into memory in one go.

JasonTheKitten commented 6 years ago

Oh, ok