我现在正在寻找其他方法来逐行读取文本文件,以实现跨平台兼容性(Windows / Linux)。
我目前的解决方案是使用SDL2在文本文件中查找(或查找)换行符(换行)。
为了演示,我有一个简单的文本文件,只有2行乱七八糟的文本:
Hello world,
This is a new line with a line break.
在某些文本编辑器上,您可以显示换行符或换行符,上面的文本看起来有点像这样:
Hello world,↵
This is a new line with a line break.
我希望使用SDL_RWops
,如果可能的话,使用SDL_RWseek
或(SDL_RWops*)->seek(SDL_RWops*)
查找换行符(换行),在上面的示例中以↵
表示。这样,我就可以编写一个短时间的SDL_RWreadToLine
版本,或者某种允许我逐行获取文本的方法。
我认为,使用psuedo代码检查是否到达换行符时,当前的方法效率很低:
//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.
}
考虑到我从一个可能包含多个字节的文本文件中读取的内容,我确信可能遗漏了一些bug。
这就是为什么我想寻找SDL2替代品的原因。
逐行读取文本的更好方法吗?
发布于 2017-12-26 02:18:49
而不是使用SDL2 2‘S SDL_RWops
,而只是使用C++标准库。
std::ifstream
和std::getline()
的结合应该能一行行地从文本文件中读取字符串。
//File reading/writing (We're only going to read)
std::ifstream edict2("dict/edict2u");
if (edict2.is_open() && edict2.good()) {
std::string buffer;
while (std::getline(edict2, buffer)) {
//Do something about the buffer.
doAction(buffer);
//Then clear the buffer once you're done with it.
buffer.clear();
};
}
感谢@Tyyppi_77指出了显而易见的事情。
https://gamedev.stackexchange.com/questions/152507
复制相似问题