Wolfgang Chien's Homepage | Delphi學習筆記 - 問答篇 |
我使用 FileOpen 指令來開檔, 然後用 FileRead 來讀取, 然後用 FileWrite 寫入, 如下..
> Var > str1:string; > > ff:=FileOpen('AAA'); > ff2:=FileOpen('BBB'); > i:=FileRead(ff,str1,10); > i:=FileWrite(ff2,str1,10); > > 這樣是能正常運作的,,可是若我直接指定 > str1:='123456789'; > 再做 i:=FileWrite(ff2,str1,9); > 寫入的結果會變成 > @12345678 > > @ = Ascii (01)
怎麼試都不行...
說來話長了, 應該是 Delphi 1.0 吧! 我們直接看您提出來的程式, 小弟作了一點修改:
procedure TForm1.Button1Click(Sender: TObject); var str1: string; i: longint; ff, ff2: THandle; begin ff := FileOpen('d:\temp\temp5\AAA.txt', 0); ff2 := FileCreate('d:\temp\temp5\BBB.txt'); i:=FileRead(ff, str1, 10); ShowMessage('*' + str1[0] + '*'); { <--- 1 } str1 := '1234567890'; ShowMessage('*' + str1[0] + '*'); { <--- 2 } i:=FileWrite(ff2, str1, 10); FileClose(ff); FileClose(ff2); end;
當您跑過上述程式後, 應該就恍然大悟了.
Pascal Style String 也是字串陣列, 只是陣列的第零個註標用來記錄字串的長度, 您原先的程式可以跑, 因為 Str 被作為指標, 而 Str[0]存的是第一個讀到的字元.
後來, 執行過 str1 := '1234567890'; 之後, Str[0] 為 #10 (以我改後的程式為例), 結果呢? 當然不是您要的結果.
所以, 上述的程式如果改用 null-terminated 字串 (這才是FileRead, FileWrite 用的正確型別), 相信就可以如您所願了.
[修改後的程式]
procedure TForm1.Button1Click(Sender: TObject); var szBuffer: array[0..10] of char; sPascal: string; i: longint; hInput, hOutput: THandle; begin hInput := FileOpen('d:\temp\temp5\AAA.txt', 0); hOutput := FileCreate('d:\temp\temp5\BBB.txt'); i := FileRead(hInput, szBuffer, 10); sPascal := '1234567890'; StrPCopy(szBuffer, sPascal); i := FileWrite(hOutput, szBuffer, 10); FileClose(hInput); FileClose(hOutput); end;
首頁 | 學習筆記 | 主題公園 | 軟體下載 | 關於本站 | 討論信群 | 相約下次 |