Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/forums/perl/)
-   -   Perl script to search sprintf and replace with snprintf (http://www.go4expert.com/forums/perl-script-search-sprintf-replace-t16620/)

~ChaMen~ 22Mar2009 16:13

Perl script to search sprintf and replace with snprintf
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:

# Search and Replace
if ($ARGV[0] eq "")
  print "usage: file1 file2 etc. or wildcards (replaces originals in place\n)";
  $totrep = 0;
  $totfil = 0;
  foreach $filename (@ARGV)
    if(-T $filename)
      $totrep += &process($filename);
  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.

Abinila 25Feb2010 17:27

Re: Perl script to search sprintf and replace with snprintf
Your script is working fine. I have checked with some input file which containing more than 2 sprintf(buf,"%s", sourcestring) line also.

All times are GMT +5.5. The time now is 15:08.