Regardless of the platform, is it safe to use Writeln to Output?

For newer Delphi versions with OSX and Android support, is there a platform-independent detection method if Writeln before Output can be used safely?

The output documentation contains a note in which

Most processes do not have a standard output file and writing to the result causes an error. Delphi files have a standard output file if they are linked as console applications.

My main goal is to have a platform-independent logging reserve, but to avoid OS errors that can occur when the console (stdout) is missing.

For example: it would be enough to check IsConsole like this:

procedure Log(const Msg: string);
begin
  if LoggingFrameworkAvailable then
  begin
    // use the logging framework to output the log message
  end if System.IsConsole then
  begin
    // fallback to stdout logging
    WriteLn(Msg);
  end;
end;

, : " Delphi Output, IsConsole - ?".

, , "" ( /dev/null ), .

, Free Pascal? (. Windows GUI, Lazarus, ?)

+4
3

, {$ IFDEF} POSIX C API-

int fileno (FILE *stream)

. , . (, ) / , fileno -1

...

, unistd.h , stdin, stdout stderr...

STDOUT_FILENO.. 1, .

STDERR_FILENO.. 2, .

, fileno , Console, 2 1, , -1,

, , Delphi Free Pascal, Virtual Pascal GNU Pascal. Go , , .

+2

System.pas :

function CanWriteln: Boolean;
begin
{$IFOPT I+}
  {$DEFINE IOCHECK_ON}
  {$I-}
{$ENDIF}
  if TTextRec(Output).Mode <> fmClosed then
    Result := True
  else
  begin
    Rewrite(Output);
    Result := IOResult = 0;
  end;
{$IFDEF IOCHECK_ON}
  {$I+}
{$ENDIF}
end;

Windows ({$ APPTYPE CONSOLE}, " ", AllocConsole), .

+1

.

Something like that:

type
  trilean = (dunno, yes, no);

  TLogger = class(TSomething)
  private
    class var FConsoleIsSafe: trilean;
    function GetConsoleIsSafe: boolean;
  public
    property ConsoleIsSafe: boolean read GetConsoleIsSafe; 
  ....

implementation

function TLogger.GetConsoleIsSafe: boolean;
begin
  if (FConsoleIsSafe = dunno) then try
    WriteLn('test'); 
    FConsoleIsSafe:= yes;
  except
    FConsoleIsSafe:= no;
  end;
  Result:= (FConsoleIsSafe = yes);
end;
-2
source

Source: https://habr.com/ru/post/1538021/


All Articles