feat(file): Implement character read and write functions for LocalFile#1431
Conversation
6734241 to
2d43ef2
Compare
| // LocalFile::readChar | ||
| //================================================================= | ||
|
|
||
| Int LocalFile::readChar( ) |
There was a problem hiding this comment.
I have it replicating the behaviour of what the file stream functions do, fgetc in this case, unless we aren't bothered about replicating it?
There was a problem hiding this comment.
Ah ok. I inquired with Chat Gippity and it appears to be ok then:
fgetc() returns an int instead of char for a very practical reason:
It needs to be able to represent every possible char value and an extra special value — EOF — which indicates the end of the file or an error.
The problem if it returned char
- Suppose
charis 8 bits (typical), it can only hold values0to255(unsigned) or-128to127(signed). EOFis defined as a negative integer (usually-1), which must be distinguishable from any valid byte value.- If
fgetc()returnedchar, there would be no way to tell the difference between reading a byte0xFF(255) andEOF(−1) on systems wherecharis signed — they'd both appear as-1.
The solution
-
fgetc()returns anintwith a range large enough to:- Represent all possible unsigned
charvalues (0–255). - Also represent EOF as a distinct value (usually
-1).
- Represent all possible unsigned
Example
#include <stdio.h>
int main(void) {
FILE *f = fopen("data.bin", "rb");
int ch;
while ((ch = fgetc(f)) != EOF) { // ch is int, not char
printf("Byte: %02X\n", (unsigned char)ch);
}
fclose(f);
}Here:
chisintso it can holdEOF.- We cast to
(unsigned char)when we want to treat the result as a byte.
Quick summary
fgetcreturnsintso it can safely distinguish between any valid byte value andEOF.
If you want, I can also explain why getchar() follows the same rule and how it’s tied to the C standard’s type promotion rules — which is actually an interesting historical detail. Would you like me to go into that?
| // LocalFile::writeChar - Ascii | ||
| //================================================================= | ||
|
|
||
| Int LocalFile::writeChar( const Char* character ) |
There was a problem hiding this comment.
I think this should return the result of write instead of the character that was passed, or EOF, which is not an intuitive result.
There was a problem hiding this comment.
i was mostly copying what the file stream type functions return with fputc etc.
they return the character written or EOF if it failed.
This PR adds extra character handling interfaces to the File class and implements the functionality into the LocalFile class.
The ram file just implements stubs that return errors if used as character handling is not required.