Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Основная";
Текущий архив: 2003.04.21;
Скачать: [xml.tar.bz2];

Вниз

Как дописать строку в существующий файл?   Найти похожие ветки 

 
zDEUSz   (2003-04-10 14:43) [0]

Здавствуйте, уважаемые!
У меня такая ситуация: есть программа, которая по достижении строки определенной длины, записывает ее в файл.
Проблема: как сделать чтобы строка дописывалась к уже существующему файлу, в его конец.
Заранее спасибо!


 
panov   (2003-04-10 14:49) [1]

Выбери из этого то, что тебе нужно...
(это поток для ведения протокола работы)


unit uLog;

interface
uses
classes,sysutils,FileCtrl,windows;

type
TLog = class(TThread)
FFilePath: String;
FFileName: String;
FFileHandle: Integer;
FMaxSize:Int64;
FCurrSize: Int64;
FLogList: TStringList;
FArchivePath: String;
isEnd: Boolean;
FAscii: Boolean;
function A2O(Source: String): String;
function O2A(Source: String): String;
protected
procedure Execute;override;
public
property SetEnd: Boolean write isEnd;
constructor Create(
const aPathFile,aPathArchive: String;
const aMaxSize: Int64; isAscii: Boolean=True);
destructor Destroy;override;
procedure Write(s: String);
procedure Open;
procedure TestSize;
procedure Archive;
end;

implementation

constructor TLog.Create(
const aPathFile,aPathArchive: String;
const aMaxSize: Int64; isAscii: Boolean=True);
var
tmpStr: String;
begin
inherited Create(True);
FreeOnTerminate := True;
FAscii := isAscii;
isEnd := False;
tmpStr := ExtractFilePath(aPathFile);
if not DirectoryExists(tmpStr) then
begin
raise Exception.Create("Directory " + tmpStr + "not exists");
Exit;
end;

FFilePath := IncludeTrailingBackSlash(tmpStr);
FFileName := ExtractFileName(aPathFile);

tmpStr := ExtractFilePath(IncludeTrailingBackSlash(aPathArchive));

if not DirectoryExists(tmpStr) then
begin
raise Exception.Create("Directory " + tmpStr + "not exists");
Exit;
end;

FLogList := TStringList.Create;
FMaxSize := aMaxSize;
FArchivePath := IncludeTrailingBackSlash(aPathArchive);

Open;
Resume;
end;

procedure TLog.Open;
begin
if not FileExists(FFilePath+FFileName) then
begin
FFileHandle := FileCreate(FFilePath+FFileName);
if FFileHandle>0 then FileClose(FFileHandle);
end;

FFileHandle := FileOpen(FFilePath+FFileName,fmOpenReadWrite or fmShareDenyNone);
if not FFileHandle >0 then
begin
raise Exception.Create("File not opened");
Exit;
end;
FCurrSize := FileSeek(FFileHandle,0,2);
TestSize;
end;

procedure TLog.TestSize;
begin
if FCurrSize>FMaxSize then Archive;
end;

procedure TLog.Archive;
var
tmpStr: String;
begin
FileClose(FFileHandle);
tmpStr := FormatDateTime("ddhhnnss.mm",now);
tmpStr := FArchivePath + tmpStr;
try
if CopyFile(PChar(FFilePath+FFileName),PChar(tmpStr),False) then
begin
DeleteFile(PChar(FFilePath+FFileName));
end;
except
end;
Open;
end;

destructor TLog.Destroy;
begin
FLogList.Free;
FileClose(FFileHandle);
end;

procedure TLog.Write(s: String);
var
tmpS: PChar;
begin
if FAscii
then tmpS := PChar(FormatDateTime("dd.mm.yyyy hh.nn.ss: ",now)+s+#13+#10)
else tmpS := PChar(A2O(FormatDateTime("dd.mm.yyyy hh.nn.ss: ",now)+s+#13+#10));
FileWrite(FFileHandle,tmpS[0],Length(tmpS));
FCurrSize := FCurrSize+Length(tmpS)+2;
TestSize;
end;

function TLog.A2O(Source: String): String;
var
ps: PChar;
begin
Result := "";
GetMem(ps,Length(Source)+1);
try
CharToOemBuff(PChar(Source),ps,Length(Source));
Result := ps;
finally
FreeMem(ps);
end;
end;


function TLog.O2A(Source: String): String;
var
ps: PChar;
begin
Result := "";
GetMem(ps,Length(Source)+1);
try
OemToCharBuff(PChar(Source),ps,Length(Source));
Result := ps;
finally
FreeMem(ps);
end;
end;

procedure TLog.Execute;
begin
while not Terminated do
begin
Sleep(1);
if isEnd then Exit;
end;
end;

end.


 
MBo   (2003-04-10 14:50) [2]

Append


 
MityaP   (2003-04-10 14:59) [3]

AssignFile(F, MyFile);
Append(F);
WriteLn(F, MyText);
Close(F)


 
zDEUSz   (2003-04-10 15:47) [4]

Всем большое спасибо!
Меня почему то заклинило на openFile, а оказывается есть Append!
Еще раз всем спасибо!


 
malkolinge   (2003-04-10 16:09) [5]

Ларчик просто открывался


 
NikB   (2003-04-10 17:09) [6]

Ia toje otkroius":
{}function Str_SaveToFile(const FNameW, aStr: string; Mode: Word = fmCreate): boolean;
var
Stream : TFileStream;
begin
Result := false;
if FileExists(FNameW) then begin
Stream := TFileStream.Create(FNameW, Mode);
Stream.Seek(0,soFromEnd);
end else begin
Stream := TFileStream.Create(FNameW, fmCreate);
end;
try
if aStr<>"" then begin
Stream.WriteBuffer(Pointer(aStr)^, Length(aStr));
end;
Result:=true;
except
end;
FreeAndNil(Stream);
end;


 
Palladin   (2003-04-10 17:24) [7]

Удалено модератором


 
NikB   (2003-04-10 23:30) [8]

Удалено модератором
Примечание: Как же жди, для чего тогда удалялось



Страницы: 1 вся ветка

Форум: "Основная";
Текущий архив: 2003.04.21;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.47 MB
Время: 0.008 c
3-67168
Silver_
2003-04-03 10:35
2003.04.21
SQL (СУБД - Access)


7-67585
k-man
2003-03-02 17:59
2003.04.21
Передвижение курсора


4-67640
Aleksey Girshovskiy
2003-02-19 12:43
2003.04.21
Как получить на что открыт файл (read write...) через сеть?


1-67347
Kapitan
2003-04-08 11:54
2003.04.21
список кнопокй


7-67576
Style
2003-02-08 01:20
2003.04.21
COM порты... как проюзать





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский