Delphi does not write to txt file

Question:

The code below creates the txt file but doesn't write to it. What can it be?

procedure TForm1.Button4Click(Sender: TObject);
var
arq: TextFile;
begin
qr.Active:= true;
qr.First;
  try
    AssignFile(arq, 'd:\\tabuada.txt');
    Rewrite(arq);
    writeln(arq, 'teste');
    while not qr.Eof do
      begin
      writeln(arq, qr.FieldValues['ine'] + ';' + qr.FieldValues['cmp'] + ';' + qr.FieldValues['cbo'] + ';' + qr.FieldValues['pa'] + ';' + qr.FieldValues['idade'] + ';' + '1;' + qr.FieldValues['quant'] + ';' + qr.FieldValues['profissional'] + ';' + qr.FieldValues['cnesdescricao'] + ';' + qr.FieldValues['cbodescricao'] + ';' + qr.FieldValues['padescricao']);
      qr.Next;
      end;

    CloseFile(arq);
    ShowMessage('ok2');
  except
  end;
end;

It doesn't show an error and it doesn't show the message 'ok2'

Answer:

Before changing the file, check whether or not it exists right after AssignFile() , doing as follows:

if FileExists('d:\\tabuada.txt') then
   Append(arq)
else
   Rewrite(arq);   

Replace qr.FieldValues with qr.FieldByName() , respecting the type of fields in the database.

Varchar: qr.FieldByName('NOME_CAMPO').AsString;
Integer: qr.FieldByName('NOME_CAMPO').AsInteger;
Numeric: qr.FieldByName('NOME_CAMPO').AsFloat;
Scroll to Top