Perl script to search sprintf and replace with snprintf

Discussion in 'Perl' started by ~ChaMen~, Mar 22, 2009.

  1. ~ChaMen~

    ~ChaMen~ New Member

    Joined:
    Mar 22, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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 a moderator: Mar 22, 2009
  2. Abinila

    Abinila New Member

    Joined:
    Feb 20, 2010
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Your script is working fine. I have checked with some input file which containing more than 2 sprintf(buf,"%s", sourcestring) line also.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice