![Antiguo](http://static.forosdelweb.com/fdwtheme/images/statusicon/post_old.gif)
18/03/2005, 02:23
|
![Avatar de Eternal Idol](http://static.forosdelweb.com/customavatars/avatar65038_2.gif) | | | Fecha de Ingreso: mayo-2004 Ubicación: Lucentum
Mensajes: 6.192
Antigüedad: 20 años, 9 meses Puntos: 74 | |
Acá tenes un ejemplo utilizando un puntero, no con las funciones de sockets así te queda algo de trabajo ;)
Código:
#include <windows.h>
#include <stdio.h>
struct registro
{
char *dns;
char usuario[10];
char control;
};
void writeReg(registro *reg, FILE *Out)
{
unsigned int dnsSize = strlen(reg->dns);
fwrite(&dnsSize, sizeof(unsigned int), 1, Out);
fwrite(reg->dns, dnsSize, 1, Out);
fwrite(reg->usuario, 10, 1, Out);
fwrite(®->control, 1, 1, Out);
}
void readReg(registro *reg, FILE *In, unsigned int dnsSize)
{
reg->dns = (char*)malloc(dnsSize + 1);
ZeroMemory(reg->dns, dnsSize + 1);
fread(reg->dns, dnsSize, 1, In);
fread(reg->usuario, 10, 1, In);
fread(®->control, 1, 1, In);
}
void main()
{
registro first;
first.dns = (char*)malloc(1024);
strcpy(first.dns, "http://www.yahoo.com");
strcpy(first.usuario, "Juan");
first.control = 'N';
registro second;
second.dns = (char*)malloc(1024);
strcpy(second.dns, "http://www.google.com");
strcpy(second.usuario, "Jose");
second.control = 'Y';
FILE *Out = fopen("c:\\struct_data.txt", "w+");
writeReg(&first, Out);
writeReg(&second, Out);
free(first.dns);
free(second.dns);
fclose(Out);
FILE *In = fopen("c:\\struct_data.txt", "r+");
unsigned int regSize = 0;
fread(®Size, sizeof(unsigned int), 1, In);
registro *primero = (registro*)malloc(sizeof(registro));
readReg(primero, In, regSize);
printf("DNS %s\r\n", primero->dns);
printf("Nombre %s\r\n", primero->usuario);
printf("Control %c\r\n", primero->control);
free(primero->dns);
free(primero);
registro segundo;
fread(®Size, sizeof(unsigned int), 1, In);
readReg(&segundo, In, regSize);
printf("DNS %s\r\n", segundo.dns);
printf("Nombre %s\r\n", segundo.usuario);
printf("Control %c\r\n", segundo.control);
free(segundo.dns);
fclose(In);
}
En cuanto a lo que comentas sobre los caracteres basura, estos estan en memoria realmente y por eso los escribe en el archivo, usá ZeroMemory para escribir todos los bytes a cero y listo.
__________________ ¡Peron cumple, Evita dignifica! VIVA PERON CARAJO
Última edición por Eternal Idol; 18/03/2005 a las 02:24 |