EMBarbosa
EMBarbosa

Reputation: 1493

Why does writing to a file fail when it's opened with FILE_FLAG_NO_BUFFERING?

I'm trying to measure the effects of FILE_FLAG_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING on a sequence of writes in a file, as request in another question. But I've found that I can't write a file with FILE_FLAG_NO_BUFFERING set.

When I use it, Delphi returns EWriteError with message stream read error.

The code used is below:

procedure TForm1.btn1Click(Sender: TObject);
var
  fsFSArquivoAAC: TFileStream;
  L, lastErr: Cardinal;
  R: WideString;
  hn: THandle;
begin
  hn := Windows.CreateFile( PChar('TesteAAC.AAC2'),
              GENERIC_READ or GENERIC_WRITE,
              FILE_SHARE_READ or FILE_SHARE_WRITE, nil, CREATE_ALWAYS,
              FILE_ATTRIBUTE_NORMAL  or FILE_FLAG_WRITE_THROUGH or FILE_FLAG_NO_BUFFERING, 0);

  lastErr := GetLastError();

  if (lastErr <> ERROR_SUCCESS) then
  begin
    if (lastErr <> ERROR_ALREADY_EXISTS ) then
    begin
      MessageDlg('Whoops, something went wrong with CreateFile!',
                  mtError, [mbOK], 0);
    end
    else
    begin
      SetLastError(ERROR_SUCCESS);
    end;

  end;

  fsFSArquivoAAC := TFileStream.Create( hn );

  try
    R := 'BatatinhaquandoNasceEspalharamapelochao';

    // write WideString
    L := Length(R);
    fsFSArquivoAAC.WriteBuffer(L, SizeOf(integer));
    if L > 0 then
      fsFSArquivoAAC.WriteBuffer(R[1], L * SizeOf(WideChar));
  finally
    fsFSArquivoAAC.Free;
  end;

If you comment FILE_FLAG_NO_BUFFERING the code works. Why?

Upvotes: 2

Views: 1474

Answers (1)

arx
arx

Reputation: 16896

If you use FILE_FLAG_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING there are various requirements for aligning your buffers in memory, aligning your writes with disk sectors and (I think) writing in multiples of sector sizes. You don't seem to be doing any of these things.

Upvotes: 7

Related Questions