c++ - 使用带有 char * 的正则表达式迭代器

标签 c++ regex string iterator

我正在尝试将文件读入缓冲区,然后使用正则表达式迭代器。我知道我可以将 C++ 字符串迭代器与正则表达式迭代器一起使用(构造函数是 std::regex_iterator<std::string::iterator> ),但我想避免将缓冲区复制到字符串中并继续使用低级函数来读取文件(现在我使用 open()read() )。

struct stat buff;
int file = open(argv[1], O_RDONLY);
if(!file)
    cout << "Error opening file" << endl;
else if(fstat(file, &buff))
    cout << "Error" << endl;
else
{
    cout << (buff.st_size) << endl;
    char fr[buff.st_size+1];

    read(file, fr, buff.st_size); // using string::c_str() or string::data() didn't work
    fr[buff.st_size] = '\0';
    // then use regex iterator to iterate through matches
}
close(file);

我认为我的选择是找到一种使用 read() 的方法使用 C++ 字符串而不是 char * 或在 char 数组上使用正则表达式迭代器的方法。我可以写一个,但我也在努力让我的程序尽可能小。

有什么办法可以做到吗?如何将 C++ 字符串用作 C char *(对于 read())?

最佳答案

只需使用 std::regex_iterator<char*> .指针本身就是一个很好的双向迭代器。另外,避免在堆栈上分配一个大的 char 数组,它可能会溢出。相反,使用堆:

std::unique_ptr<char[]> fr = new char[buff.st_size + 1];

关于c++ - 使用带有 char * 的正则表达式迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30538848/

相关文章:

c++ - gcc (Linux/MinGW) 是否存在编译器标志以在运行时引发被零除的错误?

c++ - 双重比较(再次)

C++ 从函数签名中提取参数

c++ - 使用 VMIME/libcurl 不通过服务器发送电子邮件(或 : SMTP server library)

php - 用于分解多项式表达式的正则表达式

python - 正则表达式数字之间的整个字符串匹配

sql - PostgreSQL-拆分行

类似于 GraphQL 的 C# 文本解析器

java - 如何在 Android 中使用 Java 代码在 string.xml 中添加字符串?

字符串检查 Python