Page 1 of 1
How do I use SaveToFile in order to...?
Posted: 26 Jan 2015 12:54
by pjj
1. SaveToFile adds newline at the end of the saved file -- is it intentional? How can I not write this newline?
2. I understood, perhaps erroneously, that it would be possible to save strings as ANSI, UTF-8 and even UTF-16; is it in fact possible now? How do I do this?
Please take your time; I don't need these answers right now.
Re: How do I use SaveToFile in order to...?
Posted: 26 Jan 2015 13:14
by Rickard Johansson
Maybe streams are are a better choice. I've fixed the issues and I'll release v10.20 beta in a few days.
I've also made some updates to the help file.
You could use
Code: Select all
// Read an UTF8 file to a string.
WORD mode = fmOpenRead;
TFileStream stream = TFileStream.Create("C:\\Test.txt", mode);
try
{
String s = stream.ReadString(s, encUTF8);
int len = Length(s);
...
}
finally
{
stream.Free;
};
// Write a string to an UTF8 file.
WORD mode = fmCreate or fmOpenReadWrite;
TFileStream stream = TFileStream.Create("C:\\Test.txt", mode);
try
{
String s = "Hello World!";
stream.WriteString(s, encUTF8);
}
finally
{
stream.Free;
};
Re: How do I use SaveToFile in order to...?
Posted: 26 Jan 2015 14:25
by pjj
Thanks a lot! Alas, your code for reading (and also writing) stream doesn't work for me: I get "Not enough actual parameters" error on this line:
When I change
int to
var (since it's JavaScript, not Delphi), or simply comment out this line, I get "Incompatible types: 'TEncoding', 'TEncodings'" error (and no, it's not mismatched encodings error on my side, since the file I want to read has only Latin letters.)
By the way, how can I find out if a file I want to read doesn't exist? Is s variable simply null? (I want to append some text to an existing file.)
Re: How do I use SaveToFile in order to...?
Posted: 26 Jan 2015 17:25
by Rickard Johansson
This code will work in v10.20.
Code: Select all
{
String s = "";
string sz = "C:\\Test.txt";
var size = FileSize(sz);
if (FileExists(sz)) {
Word mode = fmOpenReadWrite;
TFileStream stream = TFileStream.Create(sz, mode);
try
{
s = stream.ReadString(size, encAnsi);
s = s + "This text is appended to an existing text file...";
}
finally
{
stream.Free;
};
mode = fmOpenReadWrite;
} else {
mode = fmCreate or fmOpenReadWrite;
s = "New text file..."
}
// Write to the text file.
TFileStream stream = TFileStream.Create(sz, mode);
try
{
stream.WriteString(s, encAnsi);
}
finally
{
stream.Free;
};
}
I've added a few new functions. FileExists(), DirectoryExists() and FileSize().
Re: How do I use SaveToFile in order to...?
Posted: 26 Jan 2015 18:23
by pjj
This is truly great! Thank you! So, I will finally be able to complete my handy (I hope so) script.