使用fgets搜索字符和/或正则表达式

时间:2013-01-25 19:25:57

标签: c regex fgets

我有这个简单的代码块,用fgets()读取文件中的一行。 现在我想在这一行搜索是否有“{”或“}”并对评论的那些进行忽略评论。对于函数{和}我想添加这样的评论//这是一个很好的{。我怎么能设法做到这一点?我应该使用正则表达式吗?我删除了while循环以简化逐行迭代。

我可以以某种方式使用mystring,我认为是一个数组吗?我可以追加修改它的mystring吗?或者我要做的是创建一个新数组,将mystring放入其中然后放置注释。

例如:myfile.txt

/* Hello {} */
function
{
  hello();
}

输出

/* Hello {} */ //Ignored
function
{ //This is a good {
  hello();
} //This is a good }

我的简单块:

#include <stdio.h>
int main()
{
    FILE * pFile;
    char mystring [100];

    pFile = fopen ("myfile.txt" , "r");
    if (pFile == NULL) perror ("Error opening file");
    else {
        if ( fgets (mystring , 100 , pFile) != NULL )
            puts (mystring);
        fclose (pFile);
    }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

这可以是有用的http://www.lemoda.net/c/unix-regex/index.html

我或许能够提供代码..

答案 1 :(得分:0)

这是一个简单的方法,你如何处理你的mystring。

char *ptr=strchr(mystring,'{');
if(ptr)
{  
   sprintf(mystring,"%s //This is a goof {",mystring);
}
else
{
  ptr=strchr(mystring,'}');
  if(ptr)
  {
     sprintf(mystring,"%s //This is a goof }",mystring);
  }
}

希望这有帮助。

相关问题