首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用SDL_RWops和SDL_RWseek逐行读取文本文件?

如何使用SDL_RWops和SDL_RWseek逐行读取文本文件?
EN

Game Development用户
提问于 2017-12-25 18:41:04
回答 1查看 1.4K关注 0票数 0

我现在正在寻找其他方法来逐行读取文本文件,以实现跨平台兼容性(Windows / Linux)。

我目前的解决方案是使用SDL2在文本文件中查找(或查找)换行符(换行)。

为了演示,我有一个简单的文本文件,只有2行乱七八糟的文本:

代码语言:javascript
运行
复制
Hello world,
This is a new line with a line break.

在某些文本编辑器上,您可以显示换行符或换行符,上面的文本看起来有点像这样:

代码语言:javascript
运行
复制
Hello world,↵
This is a new line with a line break.

我希望使用SDL_RWops,如果可能的话,使用SDL_RWseek(SDL_RWops*)->seek(SDL_RWops*)查找换行符(换行),在上面的示例中以表示。这样,我就可以编写一个短时间的SDL_RWreadToLine版本,或者某种允许我逐行获取文本的方法。

我认为,使用psuedo代码检查是否到达换行符时,当前的方法效率很低:

代码语言:javascript
运行
复制
//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替代品的原因。

有人知道用SDL2?

逐行读取文本的更好方法吗?

EN

回答 1

Game Development用户

回答已采纳

发布于 2017-12-26 02:18:49

而不是使用SDL2 2‘S SDL_RWops,而只是使用C++标准库。

std::ifstreamstd::getline()的结合应该能一行行地从文本文件中读取字符串。

代码语言:javascript
运行
复制
//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指出了显而易见的事情。

票数 -1
EN
页面原文内容由Game Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://gamedev.stackexchange.com/questions/152507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档