Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用fgets搜索字符和/或正则表达式_C_Regex_Fgets - Fatal编程技术网

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

C 使用fgets搜索字符和/或正则表达式,c,regex,fgets,C,Regex,Fgets,我有一个简单的代码块,它使用fgets()读取文件中的一行。 现在我想在这一行中搜索是否有一个“{”或“}”,并在已注释的注释上放置一个忽略注释。对于函数{和},我想添加这样的注释//这是一个很好的{。我如何才能做到这一点?我应该使用regex吗?我删除了while循环以简化逐行迭代 我可以使用mystring吗,我认为它是一个数组?我可以附加mystring来修改它吗?或者我要做的是创建一个新数组,将mystring放入其中,然后在放入注释之后 例如:myfile.txt /* Hello {

我有一个简单的代码块,它使用fgets()读取文件中的一行。 现在我想在这一行中搜索是否有一个“{”或“}”,并在已注释的注释上放置一个忽略注释。对于函数{和},我想添加这样的注释//这是一个很好的{。我如何才能做到这一点?我应该使用regex吗?我删除了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;
}
#包括
int main()
{
文件*pFile;
char mystring[100];
pFile=fopen(“myfile.txt”、“r”);
如果(pFile==NULL)perror(“打开文件时出错”);
否则{
if(fgets(mystring,100,pFile)!=NULL)
puts(mystring);
fclose(pFile);
}
返回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);
  }
}

希望这有帮助。

你知道为什么如果我把:char*ptr=strchr(str,{\0');它会检测我文件中每一行的所有换行符吗?我想变得聪明,所以我说只检测{后跟一个行尾,因此注释中的字符应该被忽略?strhr只查找给定字符串中的一个字符。要从字符串的末尾进行搜索,可以使用strrchr。这些函数返回给定字符串中第一个出现的字符。使用指针算法,可以查找字符串中最后一个最短字符是否为g与否。