Oct 4, 2001, 2:16 AM
Here is my guess.
Re: This count does not work.
to be onest, your code had some strange lines in it.
You can't write to a file when you've just opened it. That overwrites the data. Also very strange is your "file copying" procedure. (if that's wat you wanted to do). Please open a file once, and keep it open. Opening a file for every write and then closing it doesn't do you any good. Other scripts get the opportunity to open the file. Both read/writes to the same file will result in some strange file (mixed ascii's, or corruped files). It even get's worse when the file isn't locked.
I hope my code can help you, since I don't know the exact context of the code in your program I can't tell you that this works literally as it has been typed.
# -w is very remommented at the #! line
use strict; # Explicit declarations
use CGI qw(:cgi);
use CGI::Carp qw(fatalsToBrowser);
use Fcntl qw(:DEFAULT :flock);
# Get parameters using CGI module
my $ID = param('id');
# Save an array with new data.
# you can't write to a file when you still need
# to read from it.
# Open and lock (LOCK_SH for read, LOCK_EX for write mostly)
# The O_RDWR makes the file readable and writable at the same time.
# P.S. you can't write until you're done reading
# That was one bug in your code.
sysopen(COUNT, "$datapath/orders/completed/count.txt", O_RDWR) or die "Can't open count.txt: $!";
while(my $num = <COUNT>)
chomp $num; # remove \n
my $newnum = ($num + 1);
# Open the new id
open(ID, "$datapath/orders/$ID.txt") or die "Can't open data file for $ID: $!";
# Just open the file once. We keep in in use until we're done.
# Combined with the flock, nobody can edit the file while this script
# is running. Otherwise someother user (running the script at the same time)
# could corrupt the entire file while we were busy with it at the same time.
open(CART, ">$datapath/orders/completed/$newnum.txt") or die "Can't save $newnum: $!";
#### The following code it don't get: there are better ways of copying a file.
#### Besides, you were opening the file for each print,
#### and truncating it every time you opened it. (because of the >, not >> )
# while(my $line = <ID>)
# chomp $line;
# my ($item, $quant, $price, $num, $total) = split(/\|/, $line, 5);
# print CART "$item|$quant|$price|$num|$total|\n";
# It can be done with this line...
pring CART <ID>; # <ID> returns an array because print can handle it.
# and everything is being printed in the the new file
# Close and unlock the files
print qq|This order has been given the number $newnum for further referencing.|;
push @NewCounts, "$newnum";
seek(COUNT, 0, 0) or die "Can't rewind file: $!"; # go to the first line
truncate(COUNT, 0) or die "Can't truncate file: $!"; # erase everything from the first character.
# Write the new data into the file,
# we're done reading from it now.
print COUNT, @NewCounts;
# Close the count file