views:

219

answers:

3

Wich is the best way to read and parse an Fixed Width Text File using Delphi?

exist any component for that?

thanks in advance.

A: 

You could do with a simple TMemo or TRichEdit. But the #1 (?) text editor component for Delphi, I believe, is TSynEdit.

Andreas Rejbrand
@Andreas i need process (parse) the file not load.
Salvador
+4  A: 

If by read you mean parse, try using a TStringList. Call TStringList.LoadFromFile and you'll get a list of individual lines. Then you can go over each individual line and parse it out into a record or class based on the various fixed-length columns in the line. Check out the Copy function for a way to make this easier.

It's hard to be more specific without any details about what you're trying to do, but that's the general idea.

Mason Wheeler
+2  A: 

If its fixed width and ansi, you can use streams to read into a record containing fields made up of array of ansichar.

type
  rTest = record
    Field1 : array[1..12] of ansichar;
    Field2 : array[1..02] of ansichar;
    CRLF   : array[1..02] of ansichar;
  end;

var
  // Sample record for testing.
  Test1 : rTest = (Field1 : '123456789012'; Field2: 'AB'; CRLF: ^M+^J);

procedure TForm1.Button1Click(Sender: TObject);
var
  St : tStream;
  rdest : rTest;
  SVar : string;
begin
  St := TMemoryStream.Create;
  // write the record from the constant 
  st.Write(Test1,SizeOf(rTest));
  st.Seek(0,soFromBeginning);
  // read the record from the stream
  St.Read(rDest,SizeOf(rTest));
  // pull out field 1 and display
  SVar := Copy(rDest.Field1,1,12);
  ShowMessage(SVar);
  // pull out field 2 and display
  SVar := Copy(rDest.Field2,1,2);
  ShowMessage(SVar);
  st.free;
end;
skamradt