Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Edición de archivo txt de fichadas (https://www.clubdelphi.com/foros/showthread.php?t=85182)

cardanver 11-02-2014 19:02:57

Edición de archivo txt de fichadas
 
Estimados, buenas tardes.
Recurro a ustedes para consultarles que me recomiendan:
tengo un archivo arch1.txt con el siguiente formato:
102 06/02/2014 5:57
19 06/02/2014 6:07
8 06/02/2014 8:25

y tengo que generar un arch2.txt editandolo de esta manera:
102 06/02/2014 05:57
019 06/02/2014 06:07
008 06/02/2014 08:25

Como verán tengo que hacer un arch2.txt de posición fija, es decir, 3 dígitos al comienzo, espacio, 10 caracteres para la fecha, espacio, 5 caracteres para la hora.

La apertura del primer archivo y su lectura lo tengo hecho, el tema es que no se me ocurre como editar el arch2.txt para que tome los cambios.
Pense en guardar todo en un memo pero el archivo es largo y la idea seria a medida que leo el primer renglón de arch1.txt, editarlo si es necesario y guardar el nuevo registro en el arch2.txt.
Ustedes que opinan es viable hacerlo de esta manera?
Desde ya, muchas gracias.
Saludos.

crespopg 11-02-2014 21:16:31

Esperando que este codigo te pueda ayudar. Saludos.
Código Delphi [-]
uses pant7;
var
 arcs,arch:text;
 dias,mess,anos,hors,mins,temps,strt2,strt1:string;
 dia,mes,ano,hor,min,temp:integer;
 err1:word;
 Begin
 If Exist('arch1.txt') Then
  Begin
   assign(arch,'arch1.txt');Reset(arch);
   assign(arcs,'arch2.txt');Rewrite(arcs);
   repeat
    readln(arch,strt1);
    strt2:=copy(strt1,1,pos(' ',strt1)-1);
    val(strt2,temp,err1);
    strt1:=copy(strt1,pos(' ',strt1)+1,length(strt1));
    val(copy(strt1, 1,2),dia,err1);
    val(copy(strt1, 4,2),mes,err1);
    val(copy(strt1, 7,4),ano,err1);
    val(copy(strt1,11,2),hor,err1);
    val(copy(strt1,14,2),min,err1);
    str(temp,temps);
          if temp<=9  then temps:='00'+temps
    else  if temp<=99 then temps:='0'+temps;
    str(mes,mess);if mes<=9  then mess:='0'+mess;
    str(dia,dias);if dia<=9  then dias:='0'+dias;
    str(ano,anos);
    str(hor,hors);if hor<=9  then hors:='0'+hors;
    str(min,mins);if min<=9  then mins:='0'+mins;
    writeln(temps+' '+dias+'/'+mess+'/'+anos+' '+hors+':'+mins);
    writeln(arcs,temps+' '+dias+'/'+mess+'/'+anos+' '+hors+':'+mins);
   until Eof(arch);
   close(arch);
   close(arcs);
  end
 Else Begin writeln('error. no existe el archivo arch1.txt'); End;
End.
102 06/02/2014 5:57
19 06/02/2014 6:07
8 06/02/2014 8:25

06/02/2014 5:57
06/02/2014 6:07
06/02/2014 8:25
12345678901234567890

ecfisa 11-02-2014 21:32:22

Hola cardanver.

Otra propuesta:
Código Delphi [-]
procedure FormatTxtFile(const SourceName, TargetName: TFileName);
var
  ori,des,aux: TStrings;
  i,p : Integer;
  h,m : string;
begin
  ori:= TStringList.Create;
  des:= TstringList.Create;
  try
    ori.LoadFromFile(SourceName);
    for i:= 0 to ori.Count-1 do
    begin
      aux:= TStringList.Create;
      try
        ExtractStrings([' ',' '], [], PChar(ori[i]), aux);
        aux[0]:= StringOfChar('0', 3-Length(aux[0])) + aux[0];
        p:= Pos(':', aux[2]);
        h:= Copy(aux[2], 1, p-1);
        m:= Copy(aux[2], p+1, MaxInt);
        h:= StringOfChar('0', 2-Length(h)) + h;
        m:= StringOfChar('0', 2-Length(m)) + m;
        aux[2]:= h + ':' + m;
      finally
        des.Add(Format('%s %s %s',[aux[0],aux[1],aux[2]]));
        aux.Free;
      end;
    end;
    des.SaveToFile(TargetName);
  finally
    ori.Free;
    des.Free;
  end;
end;

Ejemplo de uso:
Código Delphi [-]
 
  FormatTxtFile('C:\Pruebas\Original.txt', 'C:\Pruebas\Nuevo.txt');

Saludos :)

cardanver 12-02-2014 13:25:14

Muchas gracias por su ayuda crespopg y ecfisa...
En la brevedad pruebo las opciones...
Después subo todo el archivo así si alguno lo necesita lo usa.
Saludos y nuevamente gracias...

nlsgarcia 13-02-2014 01:34:42

cardanver,

Cita:

...tengo un archivo arch1.txt...tengo que hacer un arch2.txt de posición fija...'NNN DD/MM/YYYY HH:MM'...
Revisa este código:
Código Delphi [-]
procedure TForm1.Button1Click(Sender: TObject);
const
   IFileName = 'IFile.txt';
   OFileName = 'OFile.txt';
var
   InputFile : TStringList;
   OutputFile : TStringList;
   AuxFile : TStringList;
   AuxStr : String;
   i : Integer;

begin
   try
      InputFile := TStringList.Create;
      OutputFile := TStringList.Create;
      AuxFile := TStringList.Create;
      InputFile.LoadFromFile(IFileName);
      for i := 0 to InputFile.Count - 1 do
      begin
         ExtractStrings([' ',':'], [], PChar(InputFile[i]), AuxFile);
         AuxFile[0] := Format('%.3d',[StrToInt(AuxFile[0])]);
         AuxFile[2] := Format('%.2d',[StrToInt(AuxFile[2])]);
         AuxFile[3] := Format('%.2d',[StrToInt(AuxFile[3])]);
         AuxStr := AuxFile[0] + ' ' + AuxFile[1] + ' ' + AuxFile[2] + ':' + AuxFile[3];
         OutputFile.Add(AuxStr);
         AuxFile.Clear;
      end;
      OutputFile.SaveToFile(OFileName);
      MessageDlg('Archivo de Salida Generado Satisfactoriamente',mtInformation,[mbYes],0);
   finally
      InputFile.Free;
      OutputFile.Free;
      AuxFile.Free;
   end;
end;
El código anterior asume que la fecha del archivo de entrada viene en el formato DD/MM/AAAA como se indica en el Msg #1 y genera un archivo de salida en el formato 'NNN DD/MM/YYYY HH:MM', según se indica en el requerimiento planteado.

Espero sea útil :)

Nelson.

cardanver 13-02-2014 14:02:25

Muchas gracias nlsgarcia.
Probé los tres códigos, este ultimo me respondió mejor.
En la brevedad subo todo el soft con el entorno así queda para quien lo necesite.
Saludos a todos y muchas gracias.

cardanver 14-02-2014 16:28:12

el codigoooo
 
Estimados buen dia.
Como lo prometi subo el codigo para que si otro lo necesita lo tenga.
Le hice un par de ediciones que estan aclaradas en el mismo codigo.
A modo aclarativo el archivo1 es el log de un lector biometrico y el archivo2 es lo que necesita un soft de gestion para calcular las jornadas de los operarios.
Hay un par de lineas que se deben a que el archivo original es asi:

AC-No. Estado

102 06/02/2014 5:57
102 06/02/2014 5:57
102 06/02/2014 15:57
19 06/02/2014 6:07
19 06/02/2014 16:07
8 06/02/2014 8:25
8 06/02/2014 18:25

y en el archivo final no debe estar el titulo ni el espacio en blanco.
Código Delphi [-]
unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Label1: TLabel;
    Label2: TLabel;
    OpenDialog1: TOpenDialog;
    Edit1: TEdit;
    Button1: TButton;
    Button2: TButton;
    Label3: TLabel;
    Label4: TLabel;
    Button3: TButton;
    procedure Button2Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Label1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button2Click(Sender: TObject);

var
  InputFile : TStringList;
  OutputFile : TStringList;
  AuxFile : TStringList;
  AuxStr : String;
  i : Integer;
  IFileName :String;
  OFileName :String;
begin
  IFileName := Edit1.Text; //aqui se toma el path seleccionado por el usuario.
  OFileName := GetCurrentdir+'\'+'final.txt'; //aqui se determina el path del archivo final que es el mismo directorio de donde se saco el archivo original.
  try
    InputFile := TStringList.Create;
    OutputFile := TStringList.Create;
    AuxFile := TStringList.Create;
    InputFile.LoadFromFile(IFileName);
    InputFile.Delete (0);
    InputFile.Delete (1);
    for i := 2 to InputFile.Count - 1 do
    begin
      ExtractStrings([' ',':'], [], PChar(InputFile[i]), AuxFile);
      AuxFile[0] := Format('%.3d',[StrToInt(AuxFile[0])]);
      AuxFile[2] := Format('%.2d',[StrToInt(AuxFile[2])]);
      AuxFile[3] := Format('%.2d',[StrToInt(AuxFile[3])]);
      AuxStr := AuxFile[0] + ' ' + AuxFile[1] + ' ' + AuxFile[2] + ':' + AuxFile[3];
      OutputFile.Add(AuxStr);
      AuxFile.Clear;
    end;
    OutputFile.SaveToFile(OFileName);
    MessageDlg('Archivo de Salida Generado Satisfactoriamente',mtInformation,[mbYes],0);
  finally
   InputFile.Free;
   OutputFile.Free;
   AuxFile.Free;
  end;

  Label3.Visible:=true;
  Label4.Visible:=true;
  Label4.Caption:=OFileName;
  Button3.Visible:=true;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  If OpenDialog1.Execute then
    Edit1.Text:=OpenDialog1.FileName;
    Button2.Visible:=true;
  end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  Form1.Close;
end;
procedure TForm1.Label1Click(Sender: TObject);
begin

end;

Ahora estoy viendo como puedo hacer para que solo figuren la entrada y salida, ya que, a veces tengo en un mismo dia varias marcadas y solo son necesarias la primera y la ultima.
Si alguien tiene alguna idea, le agradeceria que la comente.
Si logro hacerlo andar vuelvo a subir el codigo completo.

Saludos y muchas gracias a todos por su ayuda.


La franja horaria es GMT +2. Ahora son las 23:42:38.

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