G
goddy
Unregistered / Unconfirmed
GUEST, unregistred user!
鎖沒有用SH_DENYWR <br>bool __fastcall TFMain::ReadDBF(String DBFFileName)<br>{<br><br> int handle, status;<br> long length;<br> /* Must have DOS Share.exe loaded for */<br> /* file locking to function properly */<br> //寫INI文件<br> RE->Lines->Add(DateTimeToStr(Now())+":寫Counter.dbf");<br> int i=0;<br><br> //如果打開文件失敗,重試1000次<br> for(i=0;i<1000;i++)<br> {<br> //打開dbf文件(共享方式,可讀寫)<br> handle = sopen(DBFFileName.c_str(),<br> O_RDWR ,SH_COMPAT ,S_IREAD|S_IWRITE);<br> //打開成功則退出循環<br>// handle = sopen(DBFFileName.c_str(), //別人在讀我打不開了<br>// O_RDWR ,SH_DENYWR ,S_IREAD|S_IWRITE);<br><br> if(handle>-1)<br> break;<br> Application->ProcessMessages();<br> }<br><br> if(handle < 0)<br> {//如果打開1000次文件還不成功,提示打開失敗<br> RE->Lines->Add(DateTimeToStr(Now())+":讀Counter.dbf失敗,有人在使用");<br> ShowMessage("有人在使用,讀No_Counter.dbf失敗");<br> return false;<br> }<br><br> //如果加鎖文件失敗,重試1000次<br> for(i=0;i<1000;i++)<br> {<br> //從98L開始加鎖10個字節<br> status = lock(handle,98L,10);<br> //如果加鎖成功,退出循環<br> if(status==0)<br> break;<br> Application->ProcessMessages();<br> }<br><br> if(status!=0)<br> {//如果加鎖1000次都失敗,提示失敗,返回<br> RE->Lines->Add(DateTimeToStr(Now())+":鎖Counter.dbf失敗");<br> close(handle);<br> ShowMessage("鎖No_Counter.dbf失敗");<br> return false;<br> }<br><br> //讀舊的文號<br> lseek(handle, 98L, SEEK_SET);<br> char buf[11];<br> if(read(handle, buf, 10)!=10)<br> {//讀取失敗時返回<br> status = unlock(handle,98L,10);<br> close(handle);<br> RE->Lines->Add(DateTimeToStr(Now())+":讀Counter.dbf失敗");<br> ShowMessage("讀No_Counter.dbf失敗");<br> return false;<br> }<br><br> //把讀取的文號加1<br> String iTmp=Now().FormatString("YYYY").ToInt()-1911;<br> buf[10]=0;<br> String sTemp=AnsiString(buf);<br> if(sTemp.SubString(1,2).Trim()!=iTmp.Trim())<br> iTmp=iTmp+"00000001";<br> else<br> {<br> iTmp=sTemp.ToDouble()+1;<br><br> }<br> COUNTERNO=iTmp;//把新文件號放在全局變量中<br><br> //把新文號寫回文件<br> lseek(handle, 98L, SEEK_SET);<br> if(write(handle,iTmp.c_str(),10)!=10)<br> {//寫入失敗,解鎖,關閉,返回<br> status = unlock(handle,98L,10);<br> close(handle);<br> RE->Lines->Add(DateTimeToStr(Now())+":寫Counter.dbf失敗");<br> ShowMessage("寫No_Counter.dbf失敗");<br> return false;<br> }<br><br> //解鎖<br> status = unlock(handle,98L,10);<br> if(status!=0)//解鎖失敗,在INI文件中記錄<br> RE->Lines->Add(DateTimeToStr(Now())+":解鎖Counter.dbf失敗");<br> close(handle);<br> Application->ProcessMessages();<br> CounterNoTwo=COUNTERNO.SubString(1,2);<br> CounterNoSix=COUNTERNO.SubString(COUNTERNO.Length()-5,6).ToInt(); //去掉前面的0<br><br> RE->Lines->Add(DateTimeToStr(Now())+":寫Counter.dbf成功:");<br> return true;<br><br>