Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Get Line Break Type (mac, Linux, Win And Binary File)

DZone's Guide to

Get Line Break Type (mac, Linux, Win And Binary File)

·
Free Resource
this code analyses the first 5*1024 bytes of data from a file and tells which break type it uses, or if it's a binary file...


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

type
  TBreakType = ( btNone, btWin, btMac, btLin, btBin );

---------

function GetBreakType( const Filename: string; const MaxDataToRead: Cardinal = 5*1024 ): TBreakType;
var
  FS: TFileStream;
  Buffer, BufferStart, BufferEnd: PChar;
begin
  Result := btNone;
  if not FileExists( Filename ) then
    raise Exception.Create( 'GetBreakType: nome de arquivo inválido' );
  try
    FS := TFileStream.Create( Filename, fmOpenRead );
    GetMem( Buffer, MaxDataToRead+1 );
    BufferEnd := ( Buffer + FS.Read( Buffer^, MaxDataToRead ) );
    BufferStart := Buffer;
    BufferEnd^ := #0;
  except
    raise Exception.Create( 'GetBreakType: erro alocando memória.' );
  end;
  try
    while Buffer^ <> #0 do begin
      if Result = btNone then
        if Buffer^ = ASCII_CR then begin
          if (Buffer+1)^ = ASCII_LF then begin
            Result := btWin;
            Inc( Buffer );
          end
          else
            Result := btMac;
        end
        else if Buffer^ = ASCII_LF then
          Result := btLin;
      Inc( Buffer );
    end;
    if Buffer <> BufferEnd then
      Result := btBin;
  finally
    FreeMem( BufferStart, MaxDataToRead+1 );
    FS.Free;
  end;
end;
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}