Looking for a perl script (windows) to delete the contents of a file

Hi All,

Im having a file named logserver.txt. I want a perl script to take a backup of that file, along with the datestamp; move the file to a different location or empty the contents of the file after backup.

Remember, the file gets generated when the related service starts. My condition is that I should not stop the service to delete the file.

I have attached a perl script that I used for the above said. It takes a backup but not moving the file. Immediate help will be highly appreciated.

thanks,
Gobi

"I should not stop the service to delete the file".

I'm not sure that's really possible, unless the service supports some kind of re-start mode. At any rate, if it DOES work, then instead of your "echo" line, try this one:

            $emptyfile=system("copy NUL: \"\" > \"$_\"");

In the UNIX shell, you'd do it in one of the following ways:

$ cat </dev/null >$outfile
$ dd if=/dev/null of=$outfile

Otherwise, I would like to empty the contents of the file instead of deleting the file. Is it possible?

Try the copy NUL: line.

Its not working. Any other suggestion would be highly appreciated.

Er, what part isn't working??

I used copy nul as per the above reply and also tried system("echo.> logserver.txt"); Nothing works.

Yes, but what is not working? Are you saying the file never gets overwritten, or that the new file contains zero bytes but is never appended to after that?

Yes, the file never gets overwritten.

Well, assuming you have the correct pathname for the file, it would seem to be a windows thing.

I tried using system("echo.> logserver.txt"); and I got the message as "The process cannot access the file because it is being used by another process."

Later, I opened the txt file and deleted the contents manually and saved it on the same place. It asked me whether to replace the existing file and I clicked Yes. This time, it got saved and the file size was 0 bytes. My question is when Im able to do it manually, why the script gives an error message? Please see that I didnt stop the service when I deleted the content and saved the file.

I'm sorry, it's a Windows thing. Windows probably has some kind of mandatory file locking mechanism. In UNIX it's generally advisory (optional). Maybe search the net and the Perl-Windows ports for dealing with "file locking"

Thanks for your valuable inputs. I will try searching in the net.

Could be when you open it later the file is no longer in use by another process. Windows does not allow files that are in use by certain processes to be opened more than once. There is no way around it that I know of.

You could replace your system() calls with perl functions. The File::Copy module can move/copy files and perls builtin "unlink" function deletes files.