I'm right now looking for alternative ways to read text files on a line-by-line basis, for cross-platform compatibility (Windows / Linux).
My current solution is to go look for (or seek out) the newline (line break) in a text file using SDL2.
To demonstrate, I have a simple text file, with just 2 lines of gibberish text:
Hello world,
This is a new line with a line break.
On some text editors, you are able to display newlines or line breaks, and the above text would look somewhat like this:
Hello world,↵
This is a new line with a line break.
I want to use SDL_RWops
, and if possible, use SDL_RWseek
, or (SDL_RWops*)->seek(SDL_RWops*)
, to find the newline (line break), denoted by ↵
in the above example. That way, I can write a shorthanded version of SDL_RWreadToLine
or some method that allows me to fetch text, line by line.
I believed the current method is very inefficient to check to see if I reached a newline, using psuedo-code:
//File reading/writing (We're only going to read)
//edict2 is a gigantic UTF-8 Japanese <-> English dictionary text file.
//That text file is useful for text operations (read/write) testing purposes.
SDL_RWops* edict2 = SDL_RWFromFile("edict2u", "r"); //The "u" stands for UTF-8 compatible.
if (edict2) {
Sint64 currentBytePointer = 0; //Holds the current pointer.
Sint64 currentReadPointer = 0; //Holds the current read pointer.
Sint64 fileSize = edict2->size(edict2); //Grabs the file size of the file.
char* buffer = new char[256]; //Some buffer to capture the read text characters.
while (currentBytePointer < fileSize && currentReadPointer != 0) {
Sint64 length = edict2->seek(edict2, 1, RW_SEEK_CUR); //Reads 1 byte from current read position.
Sint64 temp = edict2->read(edict2, buffer, length, length); //Implicit C conversion from void* to char*.
if (buffer[0] != '\0' && buffer[0] == '\n') {
//Found, do something about it
}
}
delete buffer;
}
else {
//File doesn't exist, do nothing.
}
I'm sure there are bugs that I may have missed out on, considering that I'm reading from a text file that may contain multiple bytes.
And that's why I wanted to look for SDL2 alternatives.
Does anyone know of a better way to read text line by line using SDL2?
std::ifstream
and usestd::getline()
when the file is opened. Right now, I'm experimenting how to split the line string up into multiple substrings and tokens, so I can better manage the Japanese dictionary. I'll go ahead and make an answer about C++'s standard library solution. \$\endgroup\$