PDA

Ver la Versión Completa : Guardar un tipo de dato como archivo


mordaz
02-09-2013, 21:21:40
Buenos días,

Es posible guardar un tipo de dato en un archivo y cargarlo en memoria posteriormente? Es decir tengo una variable de una Clase creada por ejemplo TMiPropiaClase esta clase tiene en su interior muchos tipo de datos distintos, se puede guardar de alguna manera el contenido de esta clase en un archivo, base de datos, etc. y después cargarla al abrir el programa nuevamente?

De antemano muchas gracias.

TOPX
02-09-2013, 21:31:36
Buenas tardes,


Guardar un type packed record - ClubDelphi (http://www.clubdelphi.com/foros/showthread.php?t=52370)
Simple read/write record .dat file - StackOverflow (http://stackoverflow.com/questions/5763247/simple-read-write-record-dat-file-in-delphi)
Trabajando con archivos de texto y binarios - Delphi al Límite (http://delphiallimite.blogspot.com/2007/09/trabajando-con-archivos-de-texto-y.html)

-

mordaz
02-09-2013, 22:04:42
Buenas tardes,


Guardar un type packed record - ClubDelphi (http://www.clubdelphi.com/foros/showthread.php?t=52370)
Simple read/write record .dat file - StackOverflow (http://stackoverflow.com/questions/5763247/simple-read-write-record-dat-file-in-delphi)
Trabajando con archivos de texto y binarios - Delphi al Límite (http://delphiallimite.blogspot.com/2007/09/trabajando-con-archivos-de-texto-y.html)

-

Gracias por responder, parece ser que es lo que necesito, lo voy a probar, yo trabajo en C++ Builder pero no debe haber gran diferencia.

Saludos

ecfisa
03-09-2013, 06:31:42
Es decir tengo una variable de una Clase creada por ejemplo TMiPropiaClase esta clase tiene en su interior muchos tipo de datos distintos, se puede guardar de alguna manera el contenido de esta clase en un archivo, base de datos, etc. y después cargarla al abrir el programa nuevamente?
Hola mordaz.

Otra opción es usar los métodos ReadComponent y WriteComponent, lo cuál podes hacer de dos formas:

Derivando tu clase de TComponent encapsulando las funciones y hacíendolas miembros de la primera, como por ejemplo:

/* TMiClase */
class TMiClase : public TComponent
{
private:
String FCadena;
int FEntero;
Double FDoble;
__published: // (solo obtendrás los valores de los miembros publicados)
__property String Cadena = { read = FCadena, write = FCadena};
__property int Entero = { read = FEntero, write = FEntero};
__property Double Doble = { read = FDoble, write = FDoble};
public:
virtual __fastcall TMiClase(TComponent* Owner);
void __fastcall SaveToFile(const String aFileName);
void __fastcall LoadFromFile(const String aFileName);
};

__fastcall TMiClase::TMiClase(TComponent* Owner):TComponent(Owner)
{
FCadena = "";
FEntero = 0;
FDoble = 0;
}

void __fastcall TMiClase::SaveToFile(const String aFileName)
{
if (this == NULL)
throw Exception("Objeto inexistente");
if (FileExists(aFileName))
DeleteFile(aFileName);

TFileStream *FS = new TFileStream(aFileName, fmCreate);
__try {
FS->WriteComponent(this);
}
__finally {
delete FS;
}
}

void __fastcall TMiClase::LoadFromFile(const String aFileName)
{
if (this == NULL)
throw Exception("Objeto inexistente");
if (!FileExists(aFileName))
throw Exception("Archivo inexistente");

TFileStream *FS = new TFileStream(aFileName, fmOpenRead);
__try {
FS->ReadComponent(this);
}
__finally {
delete FS;
}
}


/* Form1 */
void __fastcall TForm1::btnSaveClick(TObject *Sender)
{
TMiClase* MC = new TMiClase(this);

// Cargar unos datos para prueba...
MC->Cadena = "Una frase como cualquier otra";
MC->Entero = 1234;
MC->Doble = 3.141592654;

MC->SaveToFile("C:\\MiCompC.dat");
delete MC;
}


void __fastcall TForm1::btnReadClick(TObject *Sender)
{
TMiClase* MC = new TMiClase(this);

MC->LoadFromFile("C:\\MiCompC.dat");

// Mostrar
char *msg = "Cadena: %s \nEntero: %d \nDoble: %8.12f";
TVarRec vr[] = {MC->Cadena, MC->Entero, MC->Doble};
ShowMessage(Format(msg,vr,3));

delete MC;
}


O como funciones fuera de la clase, por ejemplo:

void SaveComponent(TComponent* CP, const String aFileName)
{
if (CP == NULL)
throw Exception("Objeto inexistente");
if (FileExists(aFileName))
DeleteFile(aFileName);

TFileStream *FS = new TFileStream(aFileName, fmCreate);
__try {
FS->WriteComponent(CP);
}
__finally {
delete FS;
}
}

void LoadComponent(TComponent* CP, const String aFileName)
{
if (CP == NULL)
throw Exception("Objeto inexistente");
if (!FileExists(aFileName))
throw Exception("Archivo inexistente");

TFileStream *FS = new TFileStream(aFileName, fmOpenRead);
__try {
FS->ReadComponent(CP);
}
__finally {
delete FS;
}
}


Llamadas de ejemplo:

// Guardar
...
{
SaveComponent(MC, "C:\\MiCompC.dat");
...
SaveComponent(Label1, "C:\\Label.dat");
}
// Leer
...
{
LoadComponent(MC, 'C:\\MiCompC.dat');
//...
LoadComponent(Label1, "C:\\Label.dat");
}


Saludos. :)

Edito: Toma en cuenta que sólo funciona para los miembros publicados.

mordaz
03-09-2013, 11:09:53
Hola nuevamente ecfisa,

Esta perfectamente detalla tu explicación, el punto de todo esto es que estoy usando algunas librerías ActiveX del controlador de una tarjeta electrónica que se comunica por USB, mi complicación surgió al intentar guardar uno de estos objetos que me escribe en memoria el propio dispositivo, el cual es una clase derivada de otra clase y así sucesivamente, necesito guardar un numero determinado de estos objetos para después volverlos a cargar en memoria y utilizarlos sin necesidad que me los vuelva a proporcionar el dispositivo, voy a probar las opciones que me propones y posteriormente publico como lo resolví.

Nuevamente gracias y te envió un cordial saludo.

nlsgarcia
03-09-2013, 23:26:14
ecfisa,


...Otra opción es usar los métodos ReadComponent y WriteComponent, lo cuál podes hacer de dos formas...


Pregunto: ¿El código del Msg # 4 como sería en Delphi?.

Gracias de antemano :)

Nelson.

ecfisa
04-09-2013, 00:06:46
Hola Nelson.

Como funciones independientes:

procedure SaveComponent(CP: TComponent; aFileName: TFileName);
begin
if not Assigned(CP) then
raise Exception.Create('Objeto inexistente');
with TFileStream.Create(aFileName, fmCreate) do
try
WriteComponent(CP);
finally
Free;
end;
end;

procedure LoadComponent(CP: TComponent;aFileName: TFileName);
begin
if not Assigned(CP) then
raise Exception.Create('Objeto inexistente');
if not FileExists(aFileName) then
raise Exception.Create('Archivo inexistente');
with TFileStream.Create(aFileName, fmOpenRead) do
try
ReadComponent(CP);
finally
Free;
end;
end;


Como métodos de clase:

...
implementation

type
TMiClase = class(TComponent)
private
FStr : string;
FEnt : integer;
FDob : Double;
published
property Str : string read FStr write FStr;
property Ent : Integer read FEnt write FEnt;
property Dob : Double read FDob write FDob;
public
constructor Create(AOwner: TComponent); override;
procedure SaveToFile(const aFileName: TFileName);
procedure LoadFromFile(const aFileName: TFileName);
end;

var
MC : TMiClase;

constructor TMiClase.Create;
begin
inherited;
FStr := 'Una frase cualquiera';
FEnt := 1234;
FDob := 3.141592654
end;

procedure TMiClase.SaveToFile(const aFileName: TFileName);
begin
if not Assigned(Self) then
raise Exception.Create('Objeto inexistente');
with TFileStream.Create(aFileName, fmCreate) do
try
WriteComponent(Self);
finally
Free
end
end;

procedure TMiClase.LoadFromFile(const aFileName: TFileName);
begin
if not Assigned(Self) then
raise Exception.Create('Objeto inexistente');
if not FileExists(aFileName) then
raise Exception.Create('Archivo inexistente');
with TFileStream.Create(aFileName, fmOpenRead) do
try
ReadComponent(Self);
finally
Free
end
end;


{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
MC : TMiClase;
begin
MC := TMiClase.Create(Self);
try
MC.SaveToFile('C:\MiComp.dat');
finally
MC.Free
end
end;

procedure TForm1.Button2Click(Sender: TObject);
var
MC : TMiClase;
begin
MC := TMiClase.Create(Self);
try
MC.LoadFromFile('C:\MiComp.dat');
ShowMessage(Format('%s %s%d %s%f',[MC.Str,#10,MC.Ent,#10,MC.Dob]));
finally
MC.Free
end
end;
...


Saludos :)

nlsgarcia
04-09-2013, 01:06:41
ecfisa,


...Como funciones independientes...Como métodos de clase...


Gracias Daniel :)

Nelson.