2016-11-17 62 views
3

我想這樣做的原因是因爲我想逐行讀取文件,併爲每一行檢查它是否匹配正則表達式。我正在使用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(&regex, regexStr, 0)) { 
    fprintf(stderr, "Could not compile regex \"%s\"\n", regexStr); 
    exit(1); 
    } 

    while ((read = getline(&line, &len, file)) != -1) { 
    int match = regexec(&regex, line, 0, NULL, 0); 

    if (match == 0) { 
     printf("%s matches\n", line); 
    } 
    } 

    fclose(file); 

    return 0; 
} 
+1

請[編輯]包括一個[MCVE]認爲演示您遇到的問題,以及您看到的確切錯誤消息。 –

+0

@KenWhite示例添加! –

回答

5

char *可以轉換爲const char *沒有任何特殊的語法。這種類型的const意味着指針指向的數據不會通過這個指針被修改。

char array[] = "abcd"; // modifiable array of 5 bytes 
char *p = array;  // array can be modified via p 
const char *q = p;  // array cannot be modified via q 

下面是一些例子:

int strcmp(const char *s1, const char *s2); 
size_t strlen(const char *s); 
char *strcpy(char *dest, const char *src); 

正如你所看到的,strcmp不會修改它接收指向字符串,但你當然可以通過定期的char *指向它。

同樣,strlen不會修改字符串,而strcpy會修改目標字符串,但不會修改源字符串。

編輯:您的問題無關,與常量性轉換:

  • 你不檢查fopen()返回值,程序產生在我的系統分割的錯,因爲myfile不存在。

  • 你必須通過REG_EXTENDED編譯與新的語法如a+b*

這裏正則表達式是一個修正版本:

#define _GNU_SOURCE 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.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 (file == NULL) { 
     printf("cannot open myfile, using stdin\n"); 
     file = stdin; 
    } 

    if (regcomp(&regex, regexStr, REG_EXTENDED)) { 
     fprintf(stderr, "Could not compile regex \"%s\"\n", regexStr); 
     exit(1); 
    } 

    while ((read = getline(&line, &len, file)) != -1) { 
     int match = regexec(&regex, line, 0, NULL, 0); 
     if (match == 0) { 
      printf("%s matches\n", line); 
     } 
    } 

    fclose(file); 
    return 0; 
} 
+0

謝謝你的回答!我在我的問題中添加了一個示例,以更好地說明我正在嘗試執行的操作。我明天會回到這裏並且繼續努力,看看我能否解決我的問題,如果答案是肯定的,我會接受它。 –

+0

@JohnDoe:我爲您的具體問題更新了答案。 – chqrlie

+0

感謝您的詳細解答! –

相關問題