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

标签 c regex getline c-strings string-literals

我想这样做的原因是因为我想逐行读取文件,并为每一行检查它是否与正则表达式匹配。我正在使用 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;
}

最佳答案

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;
}

关于C - 我可以从 char * 创建一个 const char * 变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644568/

相关文章:

java - 关于正则表达式空白

代码块和 C 未定义对 getline 的引用

c++ - 在 C++ 中读取具有多个定界符的文件

javascript - 正则表达式:用于限制字母数字字符的总长度,包括所有组

c - c中的局部变量似乎靠近堆栈内存

c - microSD卡在SPI模式时序

c - 编译代码时出现LNK2019错误

php - 如何使用正则表达式获取 `<body>` 标签内的全部内容?

c - 为什么 getline() 仅返回 1 而不是返回它读取的字符 no

c - C 中的 (*p)[8] 和 *p[8] 有什么区别?