Search code examples
perlrenameunlink

Perl - File deletion not happening


I have a file in which I have to add 2 lines. For that I open the file, read the lines, add new lines and save the file as a new temp file. Now I want to delete the original file and rename the new file to original file name. But somehow it is not happening.

unlink $file;
rename($outfile,"D:/Test/Original.cxx") or die;

This is how I have tried to do it just now. Any help!


Solution

  • You should try testing the output of your commands. The unlink command returns the number of files deleted. You can use this information to test whether the file was deleted or not:

     unlink $file or die qq(Cannot delete file "$file"\n;
     rename $outfile, $file or die qq(Cannot rename file "$outfile" to "$file\n);
    

    This will give you an idea whether the unlink is failing or the rename. There's a possibility that the file is still open. If you're adding lines to the file, make sure you use close to close the file handle first:

    open my $in_fh, "<", $file or die qq(Cannot open "$file" for reading\n);
    open my $out_fh, ">", $outfile or die qq(Cannot open file "$outfile" for writing\n)
    
    ...   #What ever you're doing
    
    close $in_fh;     #Close your files, so nothing is holding them open.
    close $out_fh;
    unlink $file or qq(Cannot delete file "$file"\n);
    rename $outfile, $file or qq(Cannot rename "$outfile" to "$file"\n);
    

    On Windows, it is especially important to close all file handles before doing anything. Even a read will prevent you from doing anything to the files.