【发布时间】:2015-05-29 20:51:40
【问题描述】:
我正在尝试将文件读入缓冲区,然后使用正则表达式迭代器。我知道我可以将 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 * (for read())?
【问题讨论】:
-
应该有一个允许
const char *的表单。只要确保缓冲区是空终止的,因为它使用它的 strlen() 创建一个停止点。 -
string::data 应该可以工作,我认为这是正确的方法 - 在读取之前预先分配字符串并将其用作缓冲区。尝试使用 string::data 时遇到什么样的错误?
-
例如 Boost 正则表达式具有这些形式之一
regex_match(const charT* str,const basic_regex <charT, traits>& e,match_flag_type flags = match_default);同样可以搜索和替换。我以前用过。大多数情况下,我使用字符串迭代器开始/结束。 -
您必须预先分配字符串缓冲区,因为我认为 read() 不会为您执行此操作。您最好将缓冲区 ptr 传递给正则表达式例程。或者,您可以从缓冲区创建一个字符串。
-
@IlyaKobelevskiy
std::string::data()的问题在于它是一个const char*。