首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++中二进制文件的数据解析:以及它的正确STL?

C++中二进制文件的数据解析:以及它的正确STL?
EN

Stack Overflow用户
提问于 2013-09-26 12:33:32
回答 1查看 578关注 0票数 1

我正在尝试开发一种类似于Client方法的请求响应系统,在客户机中从服务器请求它的数据。服务器的响应以二进制格式从文件中读取并发送到相应的客户端,文件大小几乎是由120行组成的35 KB

该文件的原型如下:

代码语言:javascript
复制
line-1: abcdefghijklmnopqrstuvwxyz
line-2: abcdefghijklmnopqrstuvwxyz
line-3: abcdefghijklmnopqrstuvwxyz
line-4: abcdefghijklmnopqrstuvwxyz
line-5: (FOR CLIENT-235)abcdefghijklmnopqrstuvwxyz
line-6: abcdefghijklmnopqrstuvwxyz
line-7: (FOR CLIENT-124)abcdefghijklmnopqrstuvwxyz
line-8: abcdefghijklmnopqrstuvwxyz
.
.
.
line-119: (FOR CLIENT-180)abcdefghijklmnopqrstuvwxyz
line-120: abcdefghijklmnopqrstuvwxyz

前四行为服务器,下四行为客户端。从第五行开始,特定客户端所需的数据将是两行,即如果请求来自CLIENT-235,服务器必须保存第5行和第6行数据,以便在容器中进行未来事务并发送给它。如果同一个客户再次请求,发送第5行和第6行,而不读取整个文件。其他客户也有类似的做法。

维护一个Index文件会更容易吗?对于特定的行和信息,我需要一个Map

我想知道使用Vector或简单structures实现这一目标的最佳方法(至少更好)是什么?因为文件中的行数可能会增加,所以我需要某种动态数组吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-26 13:35:16

一种方法是使用STL的地图来实现你想要的。因为每个客户端的响应都是两行字符串,所以可以创建一个包含两个变量的结构来存储它。然后,您可以将结构插入到映射中,并以"CLIENT-X“作为索引元素。最后,使用索引检索客户端的数据。以下是一个例子:

代码语言:javascript
复制
#include <sstream>
#include <fstream>
#include <map>
#include <string>

using namespace std;

struct data
{
    string firstLine, secondLine;
    data(){ }
};

int main()
{
    ifstream file("input.txt");

    std::map<string,data> mymap;    
    stringstream ss;
    string index;
    data buffer;
    int client = 1;

    if(file.is_open())
    {
        string server[4];

        for(int i = 0; i < 4; i++) // read the first 4 lines for the server
            getline(file, server[i]);

        while(getline(file, buffer.firstLine))
        {
            getline(file, buffer.secondLine);

            // define the index value for retrieval
            ss.str("");
            ss << "CLIENT-" << client;

            // insert the client's data into the map
            mymap.insert(pair<string,data>(ss.str(), buffer));
            client++;
        }

        // retrieve the client's data
        buffer = mymap["CLIENT-1"]; // example on how to access

        // here you can do what you want, like sending to the client
        //


        file.close();
    }

    return 0;
}   
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19028410

复制
相关文章

相似问题

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