在文件中搜索 printf 语句并替换为字符串值

search printf statement in file and replace with string value

本文关键字:替换 字符串 语句 文件 搜索 printf      更新时间:2023-10-16

我正在尝试用字符串值替换所有printf语句。所以首先,我将所有行读取为一个字符串,如下所示:

 ifstream ifs;
 ifs.open(filename);
 string temp;
 string text;
 while(!ifs.eof())
 {
     getline(ifs, temp, 't');
     text.append(temp);
     temp.clear();
 }

然后我找到printf的每一行,如果找到,则用"printf statement"替换它. 我替换printf的代码:

char ch;
while(getline(is,check))
{
 ch=check[0];
    if(!isalpha(ch))
     {
      //statements..
     }
    else
     {
        string str2("printf");
        size_t found;
        found=check.find(str2);
           if(found!=string::npos)
              check="n printf statement.n";
       OriginalStr.append(check);
         check.clear();
     }

它适用于三个四行文件,如下所示:

main()
{
Hi i am Adityaram.
and i am good boy.
and you?
printf("");
{
printf("");
Aditya
printf("");
Rammm
printf("");
Kumar
printf("");
{
printf("");
printf("");
}
printf("");
}
printf("");

但在这些文件行中找不到 printf 行。

main()
{
   char ch, file_name[25],*p;
   char answer[400];
   int size=0;
   FILE *fp;
   printf("Enter the name of file you wish to see ");
   gets(file_name);
}

为什么找不到printf行?或者怎么做?任何建议将不胜感激。

由于这是一个 C 程序,因此您可能有以下行:

{

}

即打开/关闭一个块。这绝对不是空的,但它将只包含 1 个字符。在你的while i<6你在这个缓冲区结束后走得很远。因此,在此处添加检查i小于缓冲区的长度。

然后,printf 不一定是该行中的第一个表达式,例如:

if(something) printf("this");

您的代码没有拾取此内容。您需要检查"printf"作为wd中的子字符串。查看 http://www.cplusplus.com/reference/string/string/find/以获取有关在字符串中查找字符串的参考。

最后但并非最不重要的一点是,我不明白为什么您希望您的行以字母开头(检查 isalpha)。这将无法更改代码,例如

{ printf("this"); }

它适用于小型测试文件的原因是,您编写它们很可能是为了通过内部"测试",但大文件通常包含更广泛使用的 printf。

此外,缩进不是强制性的,使用制表符 (\t) 可能是简单的空格。

我明白了,通过这个简单的方式:

string RemovePrintf(string value)
{
     string RemovedPrintf,strP;
     size_t poss;
     value.insert(0," ");//insert a white-space, cause  find method not returning position if it present at begin of string.
     poss = value.find("printf");    // position of "printf" in str
     strP = ""; // get insert whitespace at "printf line".
     strP.resize(strP.length());
     if((int)poss > 0)
      RemovedPrintf.append(strP);
     else
      RemovedPrintf.append(value);
     strP.clear();
     RemovedPrintf.resize(RemovedPrintf.length());
     return RemovedPrintf;
}

这适用于小文件和大文件。顺便说一下,感谢您回答我的问题。