【问题标题】:how to parse text in C from gtktextview/gtksourceview如何从 gtktextview/gtksourceview 解析 C 中的文本
【发布时间】:2012-05-16 21:14:51
【问题描述】:

我正在使用 gtk+-2.0 和 gtksourceview-2.0 用 C 语言编写一个文本编辑器。我正在尝试对从缓冲区中提取的数据进行一些测试。目前我正在移动一对迭代器,然后得到一个由这些迭代器分隔的文本块。然后使用 strstr、strchr、...检查这个字符串。但是,移动迭代器、读取数据、然后执行测试的过程非常麻烦。

我还将整个文档(使用前面描述的过程)提取到gchar *。处理这些数据会更容易吗?我尝试在这些数据上使用 fgets 和 getline,但编译器抱怨:

warning: passing argument 3 of ‘fgets’ from incompatible pointer type /usr/include/stdio.h:624:14: note: expected ‘struct FILE * __restrict__’ but argument is of type ‘gchar *’

warning: passing argument 1 of ‘getline’ from incompatible pointer type /usr/include/stdio.h:671:20: note: expected ‘char ** __restrict__’ but argument is of type ‘gchar *’

我试过了:

  int bytes_read;
  int nbytes = 100;
  char *my_string;
  GtkTextIter start;
  GtkTextIter end;

  wholeDoc = gtk_text_buffer_get_text(tbuffer,&start,&end,TRUE);

  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getline (&my_string, &nbytes, wholeDoc);

但出现以下错误:

warning: pointer targets in passing argument 2 of ‘getline’ differ in signedness /usr/include/stdio.h:671:20: note: expected ‘size_t * __restrict__’ but argument is of type ‘int *’

我正在寻找一种方法来检查,例如,通过简单地从循环索引中减去一个来检查上一行,就像每一行都是数组的一个元素一样。我怎样才能把数据放到这个表格中?请多多包涵,我正在学习。谢谢。

【问题讨论】:

    标签: c gtk gtksourceview


    【解决方案1】:

    这里是一个如何从 GtkTexBuffer 中获取行的简单示例。

      GtkTextIter start_iter, next_iter;
      gchar *text;
    
      gtk_text_buffer_get_iter_at_offset (source_buffer, &start_iter, 0);
    
      next_iter = start_iter;
      while (gtk_text_iter_forward_line (&next_iter))
        {    
          text = gtk_text_iter_get_text (&start_iter, &next_iter);
    
          // line processing
    
          g_free (text);
          start_iter = next_iter;
        }    
    

    更多详情请阅读 GtkTextIter 的documentation

    【讨论】:

    • 谢谢@Szilárd Pfeiffer,但正如我上面所说,我已经知道如何使用移动迭代器、提取数据的过程来提取数据......我正在寻找一种更灵活的方式在数据中导航,但也许没有。我正在学习,其中一部分是想知道你是否正在艰难地做事。也许这是唯一的方法。感谢您的帮助。
    【解决方案2】:

    您可以将字符串拆分为一个字符串数组,每行一个。使用g_strsplit()。但是,如果您想将数据关联回缓冲区中的位置,则最好使用缓冲区迭代器。

    【讨论】:

    • 使用 g_strsplit ("\n")----------- 我得到一个 gchar** all_lines =-------------- ---- 我如何循环遍历 all_lines ?因为我不知道 all_lines 的长度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多