Hi all!
This is my code, I use it to save (in append mode) the output from an external process (TProcess)
My goal is to "append" to the log file, so I need to insert a newline into the FileStream, I do this in a way I'm not really convinced is the better one, or if it is safe, even if it works;
at the same time i want to store the buffer content in a string (or Result in this case) to display it (the last buffer) somewhere later in the program
What do you suggest? I mean, it works but.. do you consider it good code? Or ugly one? How could I improve it in that case?
I don't want ask IA (that way I wouldn't learn anything useful/new)
Thanks
function SaveTheFunnyLog:string;
var
Buffer: array[0..2048 - 1] of byte;
...
...
aProc:= TProcess.Create(nil);
aProc.Options:= [poUsePipes];
aProc.Execute;
...
...
//Create a FileStream to save (append) to the LOG
LogFName:= ExtractFilePath(ParamStr(0)) + 'somefile.log';
if FileExists(LogFName) then begin
aFs:= TFileStream.Create(LogFName, fmOpenReadWrite or fmShareExclusive);
aFs.Seek(0, soFromEnd); //Move to the end of the file
end else
aFs:= TFileStream.Create(LogFName, fmCreate or fmShareExclusive);
OutputStream:= TMemoryStream.Create;
repeat
BytesRead:= aProc.Output.Read(Buffer, BUF_SIZE);
OutputStream.Write(Buffer, BytesRead)
until BytesRead = 0; // Stop if no more data is available
aProc.Free;
OutputStream.Position:= 0; //Make sure all data is copied from the start
S:= LineEnding;
aFs.CopyFrom(OutputStream, OutputStream.Size);
aFs.WriteBuffer(Pointer(S)^, Length(S));
aFs.Free;
OutputStream.Free;
S:= '';
SetLength(S, Length(Buffer));
Move(Buffer[0], S[1], Length(Buffer));
Result:= S;
end;