procedure TForm1.Button1Click(Sender: TObject); 
const   
  GetPath = 'E:\Software\DevExpressVCL.v54.rar';   
  SetPath = 'E:\Software\D.rar'; 
var   
  GetStream, SetStream: TStream;   
  intNum, int: Integer;   
  buffer: PByte;   
  intBufferSize, intBlock: Integer; 
begin   
  if not FileExists(GetPath) then   
  begin
    ShowMessage('源文件不存在!');
    Exit;   
  end;   {打开源文件}   
  GetStream := TFileStream.Create(GetPath, fmOpenRead or fmShareExclusive);
  SetStream := TFileStream.Create(SetPath, fmCreate);
  intNum := GetStream.Size; //源文件大小
  SetStream.Size := intNum; //赋给目标文件
  GetStream.Position := 0;  {流指针移到开始, 复制时从这里开始}
  SetStream.Position := 0;
  intBufferSize := intNum;   
  intBlock := intBufferSize div 100;
  GetMem(buffer, intBufferSize);  //给buffer分配空间
  while intNum <> 0 do   begin     
    Application.ProcessMessages;  //避免假死     
    int := intBlock;     
    if int > intNum then       
    int := intNum;     
    GetStream.ReadBuffer(buffer^, int);     
    SetStream.WriteBuffer(buffer^, int);     
    ProgressBar1.Position := Trunc((1 - intNum / intBufferSize) * 100);     
    Dec(intNum, int);  //传了多少,减多少   
  end;
   ...//(后面省略)  
为了更好的理解while循环,求详细解释。特别是ReadBuffer那儿,不怎么理解。30分,够吧?

解决方案 »

  1.   

    就是拷贝文件,每次从GetStream读取一定的预期字节数int(可能读出的不足int,所以应该加判断)写到SetStream,Buffer为缓冲,Buffer^这么写注意看下WriteBuffer的参数类型就知道了,他不接受指针参数。其实应该对Read的返回值和int比较,然后写SetStream这样严谨。
      

  2.   

    function TStream.CopyFrom(Source: TStream; Count: Int64): Int64;
    const
      MaxBufSize = $F000;
    var
      BufSize, N: Integer;
      Buffer: PChar;
    begin
      if Count = 0 then
      begin
        Source.Position := 0;
        Count := Source.Size;
      end;
      Result := Count;
      if Count > MaxBufSize then BufSize := MaxBufSize else BufSize := Count;
      GetMem(Buffer, BufSize);
      try
        while Count <> 0 do
        begin
          if Count > BufSize then N := BufSize else N := Count;
          Source.ReadBuffer(Buffer^, N);
          WriteBuffer(Buffer^, N);
          Dec(Count, N);
        end;
      finally
        FreeMem(Buffer, BufSize);
      end;
    end;这是TStream 的源码