PDA

View Full Version : [linux C] salvare una struttura su file


huntercity
08-07-2002, 18:08
sono ancora io....:D

ho il seguente problema
ho una struttura di questo tipo

typedef struct {
char *name; /* nome dell'entrata */
mode_t tipo; /* inidica il tipo di entrata */
time_t t_modifica; /* tempo ultima modifica */
int esiste; /* Flag per vedere se il file esiste nella directory dell'host SINCD */
} info_file;

info_file entrata;

....

if (S_ISREG(tipof)) {
/* scrittura dell'entrata sul file STAT_HOST*/
entrata.name = current_entry;
printf("nome file %s \n",current_entry);
entrata.t_modifica = buffer.st_mtime;
entrata.esiste=0;
entrata.tipo=tipof;

retcode = write(fd,&entrata,sizeof(entrata));
if(retcode == -1) {
perror("scrivendo sul file locale");
exit(-1);
}


che uso per scriverla su un file
dove current_entry e' un char*

creato cosi
current_entry= (char *) malloc ( (strlen(directory) + strlen(entry->d_name) + 2) * sizeof(char));
sprintf(current_entry, "%s/%s", directory, entry->d_name);

il tutto inserito dentro un loop per scandire tutta la mia directory

il problema mi si presenta quando devo rileggere il file creato, poiche' (e credo giustamente) se faccio
while((letti = read(fyled,&comodo,sizeof(comodo))) > 0)

mi restituisce un bel segmentation fault, in quanto credo che essendo un campo char *, lui mi legga un carattere e non la stringa per intero che prima avevo salvato, mi devo mettere a leggere un carattere alla volta da file finche' non trovo lo '\0' oppure esiste un modo diverso per leggere delle stringhe a lunghezza variabile??

grazie

ilsensine
08-07-2002, 21:50
Il buffer char * va salvato e caricato a parte, ovviamente. Questo è un possibile approccio; per comodità mi salvo anche la lunghezza della stringa:

Salvataggio:
int len;
len = strlen(entrata.name);
write(fd, &entrata,sizeof(info_file));
write(fd, &len, sizeof(int));
write(fd, entrata.name,len);

Lettura;
int len;
read(fd, &entrata, sizeof(info_file));
read(fd, &len, sizeof(int));
entrata.name = (char *) malloc(len+1);
read(fd, entrata.name, len);
entrata.name[len] = '\0';

Altri approcci sono possibili.