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-02-2014
cardanver cardanver is offline
Miembro
NULL
 
Registrado: feb 2012
Ubicación: Entre Ríos, Argentina
Posts: 14
Poder: 0
cardanver Va por buen camino
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.
Responder Con Cita
  #2  
Antiguo 11-02-2014
crespopg crespopg is offline
Miembro
 
Registrado: jul 2004
Ubicación: Texcoco, Edo. de Mexico, Mex.
Posts: 16
Poder: 0
crespopg Va por buen camino
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
__________________
Guillermo Crespo Pichardo crespopg@yahoo.com

Última edición por ecfisa fecha: 11-02-2014 a las 21:29:47. Razón: Agregar etiquetas [DELPHI] [/DELPHI]
Responder Con Cita
  #3  
Antiguo 11-02-2014
Avatar de ecfisa
ecfisa ecfisa is offline
Moderador
 
Registrado: dic 2005
Ubicación: Tres Arroyos, Argentina
Posts: 10.508
Poder: 36
ecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to beholdecfisa is a splendid one to behold
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
__________________
Daniel Didriksen

Guía de estilo - Uso de las etiquetas - La otra guía de estilo ....
Responder Con Cita
  #4  
Antiguo 12-02-2014
cardanver cardanver is offline
Miembro
NULL
 
Registrado: feb 2012
Ubicación: Entre Ríos, Argentina
Posts: 14
Poder: 0
cardanver Va por buen camino
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...
Responder Con Cita
  #5  
Antiguo 13-02-2014
Avatar de nlsgarcia
[nlsgarcia] nlsgarcia is offline
Miembro Premium
 
Registrado: feb 2007
Ubicación: Caracas, Venezuela
Posts: 2.206
Poder: 21
nlsgarcia Tiene un aura espectacularnlsgarcia Tiene un aura espectacular
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.
Responder Con Cita
  #6  
Antiguo 13-02-2014
cardanver cardanver is offline
Miembro
NULL
 
Registrado: feb 2012
Ubicación: Entre Ríos, Argentina
Posts: 14
Poder: 0
cardanver Va por buen camino
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.
Responder Con Cita
  #7  
Antiguo 14-02-2014
cardanver cardanver is offline
Miembro
NULL
 
Registrado: feb 2012
Ubicación: Entre Ríos, Argentina
Posts: 14
Poder: 0
cardanver Va por buen camino
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.
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
Edicion de un DBGRID Wbarrantes OOP 21 06-10-2010 17:13:54
Edición de IP FerCastro Varios 2 10-03-2007 00:46:59
Edicion DBGrid Caro Conexión con bases de datos 2 09-06-2006 18:02:26
Como puedo cambiar la propiedad de edicion y no edicion a un StringGrid1 ctronx Varios 2 25-06-2004 23:10:19
¿Edicion de datos? m@r SQL 6 17-10-2003 17:00:44


La franja horaria es GMT +2. Ahora son las 23:47:11.


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