I am currently able to check whether a CSV file with .csv
extension is open by using this code
if (-e $filename) {
if (open(TXT,">>$filename")){
#file is closed
}
else {
#file is open
}
}
If I try this with a .txt
file instead of a .csv
file, then the test fails. It fails means the code executes if statement even when the file is opened by me whereas it should have executed else statement of the code.
But if I open a .txt
file using Excel, it fails too.
How can I ensure that the test is successful if the file is opened using Notepad or Excel?
I checked another post How do you check if a file is open using Perl? but it didn't work for me. Can someone please suggest how to work on this.
UPDATE:
if (-e $filename) {
if (open(TXT,">>$filename")){
#file is not in use
} else {
#file is in use
}
If i replace the above code with the one mentioned in the answer
open TF, "<$filename" or die "unable to open file $!"; #open the existing file
if(<TF>){
close TXT;
} else {
goto END;
}
It doesnot work. maybe i did a syntax error on line where we open the existing file. ?