How would I create a text file in Delphi

10,026

Solution 1

Maybe you can create a stringlist and save that to file:

procedure MakeAStringlistAndSaveThat;
var
  MyText: TStringlist;
begin
  MyText:= TStringlist.create;
  try
    MyText.Add('line 1');
    MyText.Add('line 2');
    MyText.SaveToFile('c:\folder\filename.txt');
  finally
    MyText.Free
  end; {try}
end;

Solution 2

There are several ways to write two lines to a text file:

Using TFile:

fn := 'out.txt';

// method 1
TFile.WriteAllLines(fn, ['Line1','Line2']);

// method 2
TFile.WriteAllText(fn, 'Line1'+sLineBreak+'Line2');

// method 3
TFile.WriteAllText(fn, 'Line1');
TFile.AppendAllText(fn, sLineBreak);
TFile.AppendAllText(fn, 'Line2');

Using TStringList:

const fn := 'out.txt';
var sl := TStringList.Create;
try
  sl.Add('Line1');
  sl.Add('Line2');
  sl.SaveToFile(fn);
finally
  sl.Free;
end;

Solution 3

Shortest answer possible:

FileCreate('filename.txt');

FileCreate is declared in System.SysUtils and is actually a function returning a THandle. (The return value is simply discarded when you don't assign it upon calling.) I'm just showing the above code for snappiness; most of the time it's not good programming practice to ignore the return value. Especially in this case where you definitely will need it further on.

The return value is INVALID_HANDLE_VALUE if the call was not successful, otherwise it holds the file handle of the newly created file. Even if you don't need to use the file right away, you'll need the handle: the file will not be accessible until the handle is released by calling the FileClose function. So, the proper shortest answer becomes

FileClose(FileCreate('filename.txt');
Share:
10,026

Related videos on Youtube

joel_kruger
Author by

joel_kruger

Updated on June 04, 2022

Comments

  • joel_kruger
    joel_kruger almost 2 years

    I have a program where users register for my program and a text file is created for them. I have tried using the CreateFile function but am not sure on the parameters. How would I create a textfile for each user as they register using this, or any other function?

    • Ken White
      Ken White over 5 years
      You can use a TFileStream, or WriteLn in a console app, or TStringList.SaveToFile if the file isn't too large (under a few hundred megs). There are dozens of existing posts here about using all of those methods; do some searching and decide which works best for your particular requirements. There's usually no need to resort to low-level API code like CreateFile for simple text file output.
    • Rudy Velthuis
      Rudy Velthuis over 5 years
      AFAIK, you can also use Writeln in a non-console app, if you write to a text file (and not to the console). But I would use TBufferedFileStream and a TTextWriter, or, like in Andreas' answer, a TStringList.
  • Rudy Velthuis
    Rudy Velthuis over 5 years
    @joel_kruger: If it worked, then you should accept the answer.