Create a text file using TFileStream

1k Views Asked by At

I tried code from the following documentation:

Reading a String and Writing It To a File

But it doesn't work and reports a compiler error:

No member named 'fmCreate' in 'System::AnsiStringT<0>'

Here is the code I tried:

TFileStream *fs; const AnsiString str = "Hello";
fs = new TFileStream("temp.txt", fmCreate);
fs->Write ((void*)str.c_str(), str.fmCreate);
2

There are 2 best solutions below

1
john On BEST ANSWER

Well it just looks like a typo. Clearly the code is trying to write the string to the file, so the length of the string is needed. Try this

TFileStream *fs; const AnsiString str = "Hello";
fs = new TFileStream("temp.txt", fmCreate);
fs->Write ((void*)str.c_str(), str.Length());

Caveat, I know nothing about VCL.

0
Remy Lebeau On

As John's answer states, there is a typo in the documentation. str.fmCreate should be str.Length() instead.

However, there are better ways to write a string to a text file that avoid this issue. For instance, by using System::Classes::TStreamWriter or System::Ioutils::TFile instead, eg:

#include <System.Classes.hpp>

const String str = _D("Hello");
TStreamWriter *sw = new TStreamWriter(_D("temp.txt"), false, TEncoding::UTF8);
sw->Write (str);
delete sw;
#include <System.IOUtils.hpp>

const String str = _D("Hello");
TFile::WriteAllText(_D("temp.txt"), str);