c++ 如何从长void* 中获取每个char* [已关闭]

u4vypkhs  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(115)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

4天前关闭。
Improve this question
我有一个c++中的void *,它包含很多日志,但是我们不知道每个日志的长度。如何将其拆分为char*,使用正则表达式或其他方法。

#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <string.h>
#include <stdlib.h>
int main()
{
    void *logs = malloc(1024);
    char eachLog[100][100];
    if (logs == NULL) {
        printf("malloc failed\n");
        return -1;
    }

    memcpy(logs, "2023/05/29 10:12:16 638377 [ debug] this is\n 1st log\n", 53);
    memcpy((char*)logs + 53, "2023/05/29 10:12:16 638378 [   err] this is 2st log\n", 52);
    memcpy((char*)logs + 105, "2023/05/29 10:12:16 638379 [  info] this is 3th log\n", 52);

    /* the logs may be like this:
    2023/05/29 10:12:16 638377 [ debug] this is\n 1st log\n2023/05/29 10:12:16 638378 [   err] this is 2st log\n2023/05/29 10:12:16 638379 [  info] this is 3th log\n
    
    What I want is:
    put the 1st log to eachLog[0];
    put the 2st log to eachLog[1];
    put the 3st log to eachLog[2];
    */

    free(logs);
    logs = NULL;
    return 0;
}
xlpyo6sf

xlpyo6sf1#

在C++代码中,读取像您这样的日志文件(带有零散的换行符)看起来像这样(没有void*,没有显式的手动内存管理,这都是由std::string & std::vector完成的)
在线演示:https://onlinegdb.com/peAvoAb0k

#include <sstream>
#include <iostream>
#include <string>
#include <regex>

using namespace std::string_literals;

// allow for extra newlines in log lines
std::istringstream log_file
{
    "2023/05/29 10:12:16 638377 [ debug] this is\n 1st log\n"
    "2023/05/29 10:12:16 638378 [   err] this is 2st log\n"
    "2023/05/29 10:12:16 638379 [  info] this is 3th log\n"
};

std::vector<std::string> load(std::istream& file)
{
    // debug regexes here : https://regex101.com/r/nt4FUG/1
    // make a regex that recognizes the "header" of a line
    // I left the groups () in for readability for now (they are not necessary) 
    static std::regex rx{"^(\\d{4})\\/(\\d{2})\\/(\\d{2})\\s+(\\d{2}):(\\d{2}):(\\d{2})\\s+(\\d+)\\s+\\[\\s+\\w+\\]\\s+"};
    std::string line;
    std::vector<std::string> lines;

    while (std::getline(file,line))
    {
        // if there is a header then a new log entry is found
        if (std::regex_search(line, rx))
        {
            lines.push_back(line);
        }
        else
        {
            // no header found, add the read line to the last log line read
            //lines.back() += ("\n"s + line); if you want to retain newlines
            lines.back() += line;
        }
    }

    return lines;
}

int main()
{
    auto log = load(log_file);

    for (const auto& line : log)
    {
        std::cout << line << "\n";
    }

    return 0;
}

相关问题