Delphi - tfilestream: write time and date to file -
i trying save line each event containing piece of text , time + date when happened.
the problem is:
- time shown chinese font
- it replaces same line on , on again
here code:
uses sysutils, classes; function log: boolean; var fs: tfilestream; : string; time : tdatetime; begin := 'boss dead!'; time := now; try fs := tfilestream.create('log.txt', fmcreate or fmopenwrite); fs.write(pchar(i +timetostr(time))^, length(i +timetostr(time))); fs.write(i, sizeof(i)); fs.free; end; end;
thank you.
usually when expect latin text, see chinese text, means interpreting ansi text though utf-16. infer intending write out utf-16 text, writing out ansi text. means have pre-unicode delphi.
as far why keep overwriting file, that's because pass fmcreate
. want open existing file in write mode, or if no file exists, create new file. win32 api function supports open_always
creation disposition. not available through tfilestream.create
. have use thandlestream
, call createfile
directly. note newer versions of delphi introduce tfile.open
exposes open_always
functionality. reasoning says using delphi old.
assuming can use thandlestream
, , call createfile
correctly, need write out utf-16 text. simplest way use widestring
. might write code this:
var ws: widestring; .... stream.seek(0, sofromend); ws := timetostr(now) + slinebreak; stream.writebuffer(pwidechar(ws)^, sizeof(widechar)*length(ws));
on other hand, perhaps chinese comes here:
fs.write(i, sizeof(i));
this code writes pointer file. sure don't want , should remove line. sake of completeness, if have unicode delphi, write text in quite similar way. this:
var s: string; .... stream.seek(0, sofromend); s := timetostr(now) + slinebreak; stream.writebuffer(pwidechar(s)^, sizeof(widechar)*length(s));
going appending stream, run this:
var hfile: thandle; .... hfile := createfile( pchar(logfilename), generic_write, file_share_read, nil, open_always, file_attribute_normal, 0 ); win32check(hfile<>invalid_handle_value); try stream := thandlestream.create(hfile); try .... code write stream goes here stream.free; end; closehandle(hfile); end;
finally, have had make lot of guesses environment in answer. in future, include delphi version use. , include clear statement of goals.
Comments
Post a Comment