这是一个关于如何编写简单文本文件的简单示例
示例来源是 - http://www.delphibasics.co.uk/RTL.asp?Name=TextFile
代码:
var
myFile : TextFile;
text : string;
begin
// Try to open the Test.txt file for writing to
AssignFile(myFile, 'Test.txt');
ReWrite(myFile);
// Write a couple of well known words to this file
WriteLn(myFile, 'Hello World');
// Close the file
CloseFile(myFile);
// Reopen the file for reading
Reset(myFile);
// Display the file contents
while not Eof(myFile) do
begin
ReadLn(myFile, text);
ShowMessage(text);
end;
// Close the file for the last time
CloseFile(myFile);
end;
如果文件被另一个进程锁定,或者已经被当前进程锁定(正如 Remy Lebeau 指出的那样),那么你会得到一个错误,如此处所述http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN /html/delphivclwin32/SysUtils_EInOutError.html
32 共享违规
这意味着另一个进程正在使用该文件,并且您无法保存更改,直到该进程使用同一文件完成。
以下代码取自该网站http://www.swissdelphicenter.ch/torry/showcode.php?id=104向您展示了如何验证文件是否已在使用中:
function IsFileInUse(FileName: TFileName): Boolean;
var
HFileRes: HFILE;
begin
Result := False;
if not FileExists(FileName) then Exit;
HFileRes := CreateFile(PChar(FileName),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if IsFileInUse('c:\Programs\delphi6\bin\delphi32.exe') then //here you need to change this with the path to the file you want to edit/write/etc
ShowMessage('File is in use.');
else
ShowMessage('File not in use.');
end;