Delphi does not write to txt file

4

The code below creates the txt file but does not 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;

No error and no 'ok2' message

    
asked by anonymous 10.11.2017 / 15:40

2 answers

1

Avoid creating empty try-excepts. The problem information will likely appear if you change the except to:

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

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

    
13.11.2017 / 14:55
3

Before changing the file make sure it exists or not soon after AssignFile() , doing the following:

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;
    
10.11.2017 / 16:09