C - 我可以从 char * 创建一个 const char * 变量吗?

6
我希望这样做的原因是我想逐行读取文件,并检查每一行是否与正则表达式匹配。我正在使用getline()函数,它将行放入一个char *类型的变量中。我尝试使用regexec()来检查正则表达式匹配,但该函数要求您提供要匹配的字符串作为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],以展示您遇到的问题,以及您看到的确切错误消息。 - Ken White
@KenWhite 示例已添加! - user6475662
1个回答

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会修改目标字符串但不会修改源字符串。 编辑:您的问题与constness转换无关:
  • 您没有检查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;
}

谢谢您的回答!我在我的问题中添加了一个例子,以更好地说明我想要做的事情。我明天会回来再进行一些工作,看看是否可以通过您的答案解决我的问题,如果可以的话,我就接受它 :)。 - user6475662
@JohnDoe:我更新了你特定问题的答案。 - chqrlie
感谢您提供详细的答案! - user6475662

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接