这是如何编写一个简单的文本文件的例子的
源一个简单的例子是 - 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 Sharing violation
这意味着另一个进程正在使用该文件,并且在使用相同文件完成该进程之前,您无法保存更改。
从本网站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;
来源
2013-04-29 21:04:01
RBA
你需要澄清你在尝试什么。只是说'Write()'或'WriteLn()'并不能告诉我们你真的想要做什么。请包括所有相关的代码。但是,错误代码32告诉我您正在尝试写入的文件已在另一个进程中打开。 – 2013-04-29 20:55:50
这个问题很简单。我只想知道如何将1行文本写入.txt文件。 – Penian4 2013-04-29 20:57:33
这在很多很多不同的网站上都有很多次的解释。 – 2013-04-29 20:58:14