Delphi does not write to txt file

Asked

Viewed 142 times

4

The code below creates the txt file but does not write to it. Which may 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;

Shows no error and does not show ok2'

  • 1

    The fact of not showing error is due to you having a Try..Except without proper treatment. Put a ShowMessage no Except with the on E.Exception do with the error message.

2 answers

3

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

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

In place qr.FieldValues replace with qr.FieldByName(), respecting the type of the bank fields.

Varchar: qr.FieldByName('NOME_CAMPO').AsString;
Integer: qr.FieldByName('NOME_CAMPO').AsInteger;
Numeric: qr.FieldByName('NOME_CAMPO').AsFloat;
  • 3

    +1 he has no problem with his code, the only "problem" there is permission of I/What is being masked in try

1


Avoid creating empty Try-excepts. Problem information will probably appear if you change the except for:

except
  on E: Exception do
    ShowMessage(E.Message);
end;

As for the problem, you may not be allowed to create a file in this directory D:, which would be solved by running the executable as an administrator, or saving in a folder other than the root. But this can only be said with certainty through code on except.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.