Delphi上的文件操作(摘)

一、使用FileStream

例1、

Code

      qFileStream.Seek(0,   sofromEnd);   
      Buffer   :
=   'I   here   add   a   string';//写入文件的字符串   
      qFileStream.Write(Buffer[
1],   Length(Buffer));//缓冲区首址   AND   写入个数。   
      
//qFileStream.Write(Pchar(Buffer)^,   Length(Buffer));这样也行   
      qFileStream.Free;
//别忘了释放   
  
end;   
    
  
//read   
  
var   
      qFileStream:   TFileStream;   
      buffer:   
string;   
      qFileSize:   Integer;   
  
begin   
      qFileStream   :
=   TFileStream.Create('Test.txt',   fmOpenRead);   
      qFileSize   :
=   qFileStream.Seek(0,   sofromEnd);   
      SetLength(Buffer,   qFileSize);
//设置你要读的字符个数。   
      qFileStream.Seek(
0,   SoFromBeginning);   
      qFileStream.Read(Pchar(Buffer)^,   qFileSize);   
      qFileStream.Free;   
      Memo1.Text   :
=   Buffer;   
  
end;   

例子2、

Procedure FileCopy( Const sourcefilename, targetfilename: String ); 
Var 
  S, T: TFileStream; 
Begin 
  S :
= TFileStream.Create( sourcefilename, fmOpenRead ); 
try 
  T :
= TFileStream.Create( targetfilename,fmOpenWrite or fmCreate ); 
 
try 
  T.CopyFrom(S, S.Size ) ; 
 
finally 
  T.Free; 
  
end
finally 
  S.Free; 
  
end
End; 

二、使用TextFile

 1.文件变量与文件名关联: 
AssignFile(VarTxt, FileName);
FileName 如果省略路径将默认当前目录。

2.初始化读写有三种方式:
(1) Reset: 只读打开, 指针移到文件头;
(2) Rewrite: 创建新文件并打开, 只写;
(3) Append: 从尾部追加, 指针当然在文件尾。
文件不存在时使用 Reset 或 Append 会引发一个I/O异常。

最后用 CloseFile 关闭文件。  

    ①读取文件内容。在以读的方式打开文件后,可以使用read和readln语句来读取文件内容,其声明代码格式分别为: 
   read和readln的区别为后者在读取数据后,将文件指针移至下一行,上次读取的数据与回车符之间的数据被忽略。
    当读取字符串时,必须用readln过程,否则读完一行数据后,再使用read读取字符串将得到空串。

    当读取整型和实型数据时,文件中的数据用空格分隔,且必须符合数据格式,否则将产生I/O错误。
    在读取文件时,还必须判断文件指针是否已到文件尾部,此时可以用Eof函数进行判断,其声明代码如下:
    function Eof(f):Boolean;
    当文件指针指到尾部时,该函数返回值为true。
    ②向文件写入数据。以写的方式打开文件后,即可向其中写入数据,写人数据使用write和 
      writeln(f,text)
   (4)使用文件变量关闭文件 
      CloseFile(f);
    关闭文件后,系统释放打开文件时使用的资源。特别是写文件时,在调用write和writeln过程时,数据先写入内存缓冲区,只有在缓冲区满或关闭文件时,才把数据真正写入磁盘文件中,因此写完数据后不关闭文件可能丢失数据。

 写文件:


procedure TfrmZcgl.AddToFile(filename, content: string);
var
  strtime:
string;
  textf:TextFile;
begin
  strtime:
=DateToStr(now)+' '+timetostr(now);
  AssignFile(textf,filename);
  
if not FileExists(filename) then
     
begin
      ShowMessage(PChar(filename
+'不存在,创建新文件'));
      Rewrite(textf);
     
end;
  Append(textf);
  writeln(textf,content
+ '        '+strtime);
  CloseFile(textf);

end;

 读文件:

procedure ReadFile(Sender: TObject);  //读文件
var rText: TextFile;
    tmp:String;
begin
  richedit2.Clear;
//清除原来的内容
  AssignFile(rText, 
'ip.txt');
  reset(rText);
  
while not EOF(rText) do
  
begin
    readln(rText,tmp);
    richedit2.Lines.Add(tmp);
  
end;
  closefile(rText);
end

  

原文地址:https://www.cnblogs.com/samsonleung/p/1277101.html