我正在尝试将文件读入缓冲区,然后使用正则表达式迭代器。我知道我可以将 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/