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?
-
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. – Ken White Aug 08 '18 at 12:14
-
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 Aug 08 '18 at 14:18
3 Answers
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;

- 1,334
- 1
- 10
- 21
-
1@joel_kruger: If it worked, then you should [accept](https://stackoverflow.com/help/someone-answers) the answer. – Rudy Velthuis Aug 08 '18 at 14:20
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;

- 23,603
- 7
- 78
- 122
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');

- 2,971
- 9
- 41
- 54