Perl script to search sprintf and replace with snprintf

~ChaMen~'s Avatar, Join Date: Mar 2009
Newbie Member
Dear all,

I am new to perl script and would need some help for my 1st script. I wrote a script to search sprintf(buf,"%s", sourcestring) and replace with snprintf(buf, sizeof(buf),"%s", sourcestring). As snprintf() requires an extra argument, so it is not a simple search-and-replace. I need to match sprintf(), grab the first argument and use it for the second argument. This script also need to check and ensure that the destination string, the first argument to sprintf(), is a characeter array and not a pointer before doing the replacement.

My code is as follows:
Code:
#!/usr/bin/perl
# Search and Replace
if ($ARGV[0] eq "")
{
  print "usage: file1 file2 etc. or wildcards (replaces originals in place\n)";
}
else
{
  $totrep = 0;
  $totfil = 0;
  foreach $filename (@ARGV)
  {
     if(-T $filename)
    {
      $totrep += &process($filename);
      $totfil++;
    }
  }
  print "$totfil files, $totrep replacements\n";
}
sub process
{
  $fn = $_[0];
  undef $/; #to grab entire file at once
  print STDERR "$fn"; #show currnt file name
  open (INFILE, $fn);
  $q = <INFILE>;
  close INFILE;
  $/ = "\n";
  $sum = 0;
    
  if ($q =~ m/char\s*([\w]+)/i)
  {
    
    $sum = ($q =~ s/\bsprintf\(([\w]+),/snprintf\(\1,sizeof\(\1\),/ig);
  }
 if ($sum > 0)
 {
    open (OUTFILE,">$fn");
    print OUTFILE $q;
    close OUTFILE;
    print " $sum replacement(s)";
 }
 print "\n";
 return $sum;
}
However, there are some error for checking the char string (once the 1st occurence of char string passed the check, it will do search-and-replace for all sprintf() to snprintf() in the file). I would need help to identify what's wrong with the script. Thanks all.

Last edited by shabbir; 22Mar2009 at 17:04.. Reason: Code blocks
Abinila's Avatar, Join Date: Feb 2010
Light Poster
Your script is working fine. I have checked with some input file which containing more than 2 sprintf(buf,"%s", sourcestring) line also.