我想這樣做的原因是因爲我想逐行讀取文件,併爲每一行檢查它是否匹配正則表達式。我正在使用getline()函數,該函數將該行放入一個char *
類型變量中。我正在嘗試使用regexec()
來檢查正則表達式匹配,但此函數要求您提供匹配的字符串作爲const char *
。C - 我可以從char *創建一個const char *變量嗎?
所以我的問題是,我可以從char *
創建一個const char *
?或者,有沒有更好的方法來解決我在這裏要解決的問題?
編輯:我被要求提供一個例子,我沒有想到,併爲沒有給予第一個地方道歉。在撰寫本文之前,我確實是通過@chqrlie閱讀了答案。以下代碼給出了分段錯誤。
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>
#include <regex.h>
int main() {
FILE * file = fopen("myfile", "r");
char * line = NULL;
size_t len = 0;
ssize_t read;
regex_t regex;
const char * regexStr = "a+b*";
if (regcomp(®ex, regexStr, 0)) {
fprintf(stderr, "Could not compile regex \"%s\"\n", regexStr);
exit(1);
}
while ((read = getline(&line, &len, file)) != -1) {
int match = regexec(®ex, line, 0, NULL, 0);
if (match == 0) {
printf("%s matches\n", line);
}
}
fclose(file);
return 0;
}
請[編輯]包括一個[MCVE]認爲演示您遇到的問題,以及您看到的確切錯誤消息。 –
@KenWhite示例添加! –