Mega Code Archive

 
Categories / Delphi / Files
 

Converting from Windows ASCII to UNIX ASCII Text Files

Title: Converting from Windows ASCII to UNIX ASCII Text Files Question: How do you convert between Windows and UNIX ASCII files? Here's how to stop Notepad from displaying a mess... Answer: Ever loaded what you beleived to be a nice text file (HTML as well) into Notepad and found it to be a complete mess? If yes then the reason is because Microsoft Windows uses CRLF (0x0D 0x0A) to end lines and UNIX, Linux, Apple Mac and most other OS's use just LF (0x0A) - they just have to be awkward don't they... Below are two routines you can use to switch between formats, it also shows an example of callbacks and streams: type TConvertNotifyKind = (nkMax, nkProgress); TConvertNotify = procedure(Kind: TConvertNotifyKind; Value: LongInt); // UnixToWin -- Convert a UNIX single LF text stream to a Windows CRLF text stream function UnixToWin(InStream: TStream; OutStream: TStream; Notify: TConvertNotify): Boolean; var B, NewB: Byte; Value: LongInt; begin if not Assigned(InStream) then begin Result := False; Exit; end; if not Assigned(OutStream) then begin Result := False; Exit; end; if Assigned(Notify) then Notify(nkMax,InStream.Size); Value := 0; while InStream.Position begin InStream.Read(B,SizeOf(Byte)); case B of $0A: begin NewB := $0D; OutStream.Write(NewB,SizeOf(Byte)); NewB := $0A; OutStream.Write(NewB,SizeOf(Byte)); end; else OutStream.Write(B,SizeOf(Byte)); end; Inc(Value); if Assigned(Notify) then Notify(nkProgress,Value); end; if Value = InStream.Size then begin if Assigned(Notify) then Notify(nkProgress,0); end; Result := True; end; // WinToUnix -- Convert a CRLF Windows text stream to single LF UNIX text stream function WinToUnix(InStream: TStream; OutStream: TStream; Notify: TConvertNotify): Boolean; var B: Byte; Value: LongInt; begin if not Assigned(InStream) then begin Result := False; Exit; end; if not Assigned(OutStream) then begin Result := False; Exit; end; if Assigned(Notify) then Notify(nkMax,InStream.Size); Value := 0; while InStream.Position begin InStream.Read(B,SizeOf(Byte)); if B $0A then begin OutStream.Write(B,SizeOf(Byte)); end; Inc(Value); if Assigned(Notify) then Notify(nkProgress,Value); end; OutStream.Seek(SizeOf(Byte),soFromEnd); OutStream.Read(B,SizeOf(B)); if B $0D then begin B := $0D; OutStream.Write(B,SizeOf(Byte)); end; if Value = InStream.Size then begin if Assigned(Notify) then Notify(nkProgress,0); end; Result := True; end; ------------------------------------------------------------------------------ P.S: If this is wrong, let me know!