Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 11-06-2008
Avatar de GaaK
GaaK GaaK is offline
Miembro
 
Registrado: oct 2005
Ubicación: Trujillo - Peru
Posts: 31
Poder: 0
GaaK Va por buen camino
Archivos de Texto con INCLUDE

Hola todos, quisiera por favor el mejor algoritmo Delphi para leer un archivo de texto que a su vez (mediante un INCLUDE) pueda llamar a otros...

Gráficamente esto podría ser algo como:

Archivo1.txt
line1
line2
INCLUDE "Archivo2.txt"
line6
INCLUDE "Archivo4.txt"
line9
<EOF>

Archivo2.txt
line3
line4
INCLUDE "Archivo3.txt"
<EOF>

Archivo3.txt
line5
<EOF>

Archivo4.txt
line7
line8
<EOF>

Donde <EOF> es el fin de cada archivo. Finalmente el propósito de leer todos los archivos es para conseguir un nuevo archivo final de la forma:
ArchivoFinal.txt
line1
line2
....
line9

Obviamente cada line contiene texto variable.

----------------------------------------
Mi idea es la siguiente:

Código Delphi [-]
var
  file1 : TextFile;
  nIncludeLevel: Integer = 0;
  filename: array[0..6] of string; { 7 levels for INCLUDE }

implementation

procedure TFormMain.FileOpen1Accept(Sender: TObject);
var
  s0: String; 
  n: Integer;
begin
  { default nIncludeLevel is zero }
  filename[nIncludeLevel] := FileOpen1.Dialog.FileName;
  AssignFile(file1, filename[nIncludeLevel]);
  Reset(file1);

  { CountLines }
  n := 0;
  while (not Eof(file1)) do begin
    Readln(file1,s0);
    if 'INCLUDE'=GetFirstWord then begin { GetFirstWord returns 'INCLUDE' and s0->"NameFile" }
      s0 := ExtractFilePath(filename[nIncludeLevel]) + AnsiDequotedStr(s0,'"'); { s0: 'Archivo2.txt' }
      Inc(nIncludeLevel); { 1 }
      filename[nIncludeLevel] := s0;
      AssignFile(file1, filename[nIncludeLevel]);
      Reset(file1);
    end
    else { salvar lineN };
    if (Eof(file1)) and (nIncludeLevel<>0) then begin
      CloseFile(file1);
      Dec(nIncludeLevel);
      { aqui se apaga mi cerebro :-( }
      // AssignFile(file1, filename[nIncludeLevel]);
      // Reset(file1);
    end;
    Inc(n);
  end;
  CloseFile(file1);
  Reset(file1);
end;


Gracias por sus respuestas.

- Gaak -
__________________
L'Gaak dice

Última edición por GaaK fecha: 11-06-2008 a las 00:19:33. Razón: syntax
Responder Con Cita
  #2  
Antiguo 11-06-2008
[coso] coso is offline
Miembro Premium
 
Registrado: may 2008
Ubicación: Girona
Posts: 1.678
Poder: 0
coso Va por buen camino
deberias usar recursividad algo asi

Código Delphi [-]
procedure Parse_token(tok : string; destino : TStringList);
var
  nombre_archivo : string;
begin
    if Pos('INCLUDE',tok) <> 0 then 
    begin 
         nombre_archivo := .... // se extrae el nombre del archivo, puedes probar borrando la palabra 'INCLUDE=' de tok
         leer_archivo(nombre_archivo,destino);
    end
    else
    destino.Add(tok);
end;

function leer_archivo(s : string; destino : TStringList) : boolean;
var
     st : TStringList;
     i, r : longint;
     tok : string;
begin
    st := TStringList.Create;

    st.LoadFromFile(s);

   ... // comprobar que se ha cargado bien , etc...

    r := st.Count;
    for i := 0 to r - 1 do
    begin
      tok := st[i];
      parse_token(tok,destino);     
    end;
  
    st.Free;
end;

procedure Iniciar;
var
   dest : TStringList;
begin
  dest := TStringList.Create;
  
  if OpenDialog1.Execute then
  begin
     Leer_archivo(OpenDialog1.FileName,dest);
     if SaveDialog1.Execute then 
     dest.SaveToFile(SaveDialog1.Filename);
  end;

  dest.Free;
    
end;
Responder Con Cita
  #3  
Antiguo 17-06-2008
Avatar de GaaK
GaaK GaaK is offline
Miembro
 
Registrado: oct 2005
Ubicación: Trujillo - Peru
Posts: 31
Poder: 0
GaaK Va por buen camino
Cita:
Empezado por coso Ver Mensaje
deberías usar recursividad...
Gracias, me inspiré en su idea y escribí el siguiente código (requiere: Form1, OpenDialog1, Button1):
Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    OpenDialog1: TOpenDialog;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

function LeerArchivo(namefile: String; destino: TStringList): Boolean;

var
  Form1: TForm1;
  sPath: String;

implementation

{$R *.dfm}

procedure ParseToken(tok: String; destino: TStringList);
begin
  tok := TrimLeft(tok);
  if (Pos('INCLUDE',tok)<>0) then begin
    { tok := 'INCLUDE "Archivo2.txt"' }
    Delete(tok, 1, 7); { 'INCLUDE' contains 7 chars }
    tok := TrimLeft(tok);
    { tok := '"Archivo2.txt"' }
    tok := AnsiDequotedStr(tok, '"');
    { tok := 'Archivo2.txt' }
    LeerArchivo(sPath+tok, destino);
  end
  else destino.Add(tok);
end;

function LeerArchivo(namefile: String; destino: TStringList): Boolean;
var
  st: TStringList;
  i, r: Longint;
  tok: String;
begin
  st := TStringList.Create;

  st.LoadFromFile(namefile);
  r := st.Count;
  for i:=0 to r-1 do begin
    tok := st[i];
    ParseToken(tok, destino);
  end;

  st.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  dest: TStringList;
begin
  dest := TStringList.Create;
  if OpenDialog1.Execute then begin
    sPath := ExtractFilePath(OpenDialog1.FileName);
    LeerArchivo(OpenDialog1.FileName, dest);
    dest.SaveToFile('ArchivoFinal.txt');
  end;
  dest.Free;
end;

end.
... para hacerlo funcionar, clic en el botón y elegir "Archivo1.txt" (mencionado arriba) y auto se creará "ArchivoFinal.txt" con todas las líneas de los INCLUDE.

Ahora, con esta misma idea no sería mejor hacerlo directamente con AssignFile etc etc?... Digo esto porque lo de crear StringList me parece consumo de memoria y tiempo?... (imaginando archivos de texto de tamaño medio ~200KB).

Iluminarme si me equivoco.

Gracias de antemano.

- Gaak -
__________________
L'Gaak dice
Responder Con Cita
  #4  
Antiguo 17-06-2008
[coso] coso is offline
Miembro Premium
 
Registrado: may 2008
Ubicación: Girona
Posts: 1.678
Poder: 0
coso Va por buen camino
Bueno la memoria esta para estas cosas. Si que es cierto q si usases directamente acceso a disco optimizarias recursos de memoria (y claro esta, tambien te iria más lento), pero no creo que lo requieras para estas cosas. Personalmente, uso la manera de trabajar : cargar a memoria, trabajar los datos, grabar resultado, la mayoria de las veces usando el TStringList q es muy buen invento. Lo maximo que he cargado usando el TStringList loadfromfile son 15 megas, pero creo que se puede usar hasta llenar la memoria entera del pc.

saludos

Última edición por coso fecha: 17-06-2008 a las 21:23:59.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Problema con archivos de texto. morodo Lazarus, FreePascal, Kylix, etc. 5 29-04-2011 02:07:03
XML vs archivos de texto jordan23 Varios 5 17-08-2007 19:18:06
Leer varios archivos de texto y extraer solo 2 lineas de ese texto mp3968 Internet 1 17-05-2007 20:24:09
Archivos de texto yekkita Varios 4 19-01-2007 20:06:03
archivos de texto ssanchez Varios 1 19-01-2007 15:44:34


La franja horaria es GMT +2. Ahora son las 05:28:49.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi