示例#1
0
static int FSWrite(const char *destination, int dd, const char *buf, size_t n_write)
{
    const void *cur = buf;
    const void *end = buf + n_write;

    while (cur < end)
    {
        const void *skip_span = MemSpan(cur, 0, end - cur);
        if (skip_span > cur)
        {
            if (lseek(dd, skip_span - cur, SEEK_CUR) < 0)
            {
                Log(LOG_LEVEL_ERR, "Copy failed (no space?) while copying to '%s' from network '%s'", destination, GetErrorStr());
                return false;
            }

            cur = skip_span;
        }

        const void *copy_span = MemSpanInverse(cur, 0, end - cur);
        if (copy_span > cur)
        {
            if (FullWrite(dd, cur, copy_span - cur) < 0)
            {
                Log(LOG_LEVEL_ERR, "Copy failed (no space?) while copying to '%s' from network '%s'", destination, GetErrorStr());
                return false;
            }

            cur = copy_span;
        }
    }

    return true;
}
int creaAppello(int fd,int servSFd){
    
    app_t appello, tmp;
    ssize_t nwrite;
    comm_t command = FAIL, response = FAIL;
    FILE *fp;
    
    FullRead(fd, &appello, sizeof(app_t));//legge le info appello
    
    if ((fp = fopen("appelli.dat", "ab+")) == NULL) {//apre il file in scrittura e se non esiste lo crea
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito al clientP
        perror("Errore apertura file: appelli.dat");
        return 0;
    }
    appello.id = 1;
    fseek(fp, -sizeof(app_t), SEEK_CUR);//sposto il cursore di appello indietro
    if(1 == fread(&tmp, sizeof(app_t), 1, fp)){//se riesco a leggere un appello
        appello.id = tmp.id + 1;//imposto l'id del nuovo appello sommando 1 a quello letto
    }
    
    nwrite = fwrite(&appello, sizeof(app_t), 1, fp);//registra appello nel file
    
    fclose(fp);
    
    if (nwrite < 0) {
        write(fd, &command, sizeof(comm_t));
        perror("errore scrittura file");
        return 0;
    }else{
        command = SUCCESS;
        write(fd, &command, sizeof(comm_t));//invio esito al clientP
        /*Invio il tutto al serverS*/
        command = NEW_APP;
        write(servSFd, &command, sizeof(comm_t));//invio al serverS il comando nuovo appello
        FullWrite(servSFd, &appello, sizeof(app_t));//gli invio i dati ricevuti dal client
        read(servSFd, &response, sizeof(comm_t));//leggo l'esito
        switch (response) {
            case FILE_ERR:
                printf("Impossibile accedere al DB\n");
                return 0;
                break;
            case SUCCESS:
                printf("Appello creato con successo!\n");
                return 1;
                break;
            case FAIL:
            default:
                printf("Qualcosa e' andato storto\n");
                return 0;
                break;
        }
        /*fine della comunicazione al serverS*/
    }
}
示例#3
0
/* Fill a buffer with non-NULL garbage. */
static void WriteBufferToFile(const char *name, const void *buf, size_t count)
{
    int fd = open(name, O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, 0700);
    assert_int_not_equal(fd, -1);

    ssize_t written = FullWrite(fd, buf, count);
    assert_int_equal(written, count);

    int close_ret = close(fd);
    assert_int_not_equal(close_ret, -1);
}
void visualizzaAppelli(int fd,user_t *connected){
    FILE *fp;
    ssize_t nread;
    app_t appello;
    app_t * daInviare;
    comm_t command = SUCCESS;
    long n = 0, i;
    
    if ((fp = fopen("appelli.dat", "rb")) == NULL) {//se ho problemi nell'apertura del file
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito negativo
        perror("Errore apertura file: appelli.dat");
        return ;
    }//altrimenti
    write(fd, &command, sizeof(comm_t));//invio esito positivo
    fseek(fp, 0, SEEK_END);
    n = ftell(fp)/sizeof(app_t); //li conta tutti
    daInviare = malloc(sizeof(app_t) * (n + 1));
    rewind(fp);
    if (connected[fd].categoria == P) {//se è un professore
        n = 0;
        while (1 == (nread = fread(&appello, sizeof(appello), 1, fp))) {//legge ogni appello
            if (!strcmp(connected[fd].matricola, appello.matricolaProfessore)) {//se ne è propritario
                daInviare[n++] = appello;//lo conta e lo inserisce nell'array
            }
        }
        write(fd, &n, sizeof(int));//invia numero di appelli
        for (i = 0; i < n; i++) {
            FullWrite(fd, &daInviare[i], sizeof(app_t));
        }
    }else{
        write(fd, &n, sizeof(int));//invia numero di appelli
        while (1 == (nread = fread(&appello, sizeof(appello), 1, fp))) {
            FullWrite(fd, &appello, sizeof(app_t));//invio n appelli
        }
    }
    fclose(fp);
    free(daInviare);
}
void visualizzaEsami(int fd){
    long appId;
    int n = 0, i;
    exam_t esame, esamiDaInviare[100];
    size_t nread;
    FILE *fp;
    
    read(fd, &appId, sizeof(long));//legge l'id dell'appello da aprire
    if ((fp = fopen("esami.dat", "rb")) == NULL) {
        perror("esami.dat");
        return;
    }
    while (1 == (nread = fread(&esame, sizeof(esame), 1, fp))) {
        if (esame.id == appId) {
            esamiDaInviare[n++] = esame;
        }
    }
    write(fd, &n, sizeof(int));//invio il numero di esami da ricevere
    for (i = 0; i < n; i++) {
        FullWrite(fd, &esamiDaInviare[i], sizeof(exam_t));
    }
}
示例#6
0
bool
Port::FullWriteString(const char *s,
                      OperationEnvironment &env, unsigned timeout_ms)
{
  return FullWrite(s, strlen(s), env, timeout_ms);
}
示例#7
0
文件: files_copy.c 项目: frerich/core
bool CopyRegularFileDisk(char *source, char *destination, bool make_holes)
{
    int sd, dd, buf_size;
    char *buf, *cp;
    int n_read, *intp;
    long n_read_total = 0;
    int last_write_made_hole = 0;

    if ((sd = open(source, O_RDONLY | O_BINARY)) == -1)
    {
        CfOut(cf_inform, "open", "Can't copy %s!\n", source);
        unlink(destination);
        return false;
    }

    unlink(destination);                /* To avoid link attacks */

    if ((dd = open(destination, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL | O_BINARY, 0600)) == -1)
    {
        close(sd);
        unlink(destination);
        return false;
    }

    buf_size = ST_BLKSIZE(dstat);
    buf = xmalloc(buf_size + sizeof(int));

    while (true)
    {
        if ((n_read = read(sd, buf, buf_size)) == -1)
        {
            if (errno == EINTR)
            {
                continue;
            }

            close(sd);
            close(dd);
            free(buf);
            return false;
        }

        if (n_read == 0)
        {
            break;
        }

        n_read_total += n_read;

        intp = 0;

        if (make_holes)
        {
            buf[n_read] = 1;    /* Sentinel to stop loop.  */

            /* Find first non-zero *word*, or the word with the sentinel.  */

            intp = (int *) buf;

            while (*intp++ == 0)
            {
            }

            /* Find the first non-zero *byte*, or the sentinel.  */

            cp = (char *) (intp - 1);

            while (*cp++ == 0)
            {
            }

            /* If we found the sentinel, the whole input block was zero,
               and we can make a hole.  */

            if (cp > buf + n_read)
            {
                /* Make a hole.  */
                if (lseek(dd, (off_t) n_read, SEEK_CUR) < 0L)
                {
                    CfOut(cf_error, "lseek", "Copy failed (no space?) while doing %s to %s\n", source, destination);
                    free(buf);
                    unlink(destination);
                    close(dd);
                    close(sd);
                    return false;
                }
                last_write_made_hole = 1;
            }
            else
            {
                /* Clear to indicate that a normal write is needed. */
                intp = 0;
            }
        }

        if (intp == 0)
        {
            if (FullWrite(dd, buf, n_read) < 0)
            {
                CfOut(cf_error, "", "Copy failed (no space?) while doing %s to %s\n", source, destination);
                close(sd);
                close(dd);
                free(buf);
                unlink(destination);
                return false;
            }
            last_write_made_hole = 0;
        }
    }

    /* If the file ends with a `hole', something needs to be written at
       the end.  Otherwise the kernel would truncate the file at the end
       of the last write operation.  */

    if (last_write_made_hole)
    {
        /* Write a null character and truncate it again.  */

        if (FullWrite(dd, "", 1) < 0 || ftruncate(dd, n_read_total) < 0)
        {
            CfOut(cf_error, "write", "cfengine: full_write or ftruncate error in CopyReg\n");
            free(buf);
            unlink(destination);
            close(sd);
            close(dd);
            return false;
        }
    }

    close(sd);
    close(dd);

    free(buf);
    return true;
}
//funzione dedicata ai servizi della segreteria studenti
void segreteria_studenti(int conn_fd, struct sockaddr_in client)
{

int sockfd,proffd,j,not_valid=1,fmenu,scelta=0,mscelta=0;
char buffer[1024],file[1024],data[50], buffer2[1024];
ssize_t nread,nread2,nread3;
char Buffer[4095];//buffer per caricare un appelo di dimensioni x
    char *filetemp = "temp.txt";//file che andrà a sostituire il file dell'appello con le modifiche apportate
    char trova[30];//buffer dedicato alla ricerca della stringa da modificare
    char sostituisci[30];//buffer dedicato alla sostituzione della stringa
    int line = 0,line2=0,invio=1;

// qui si assegna tramite la struttura un indirizzo ip e un porta per metterci in contatto col serverd per inviare un appello modificato
struct sockaddr_in serverd;
serverd.sin_family = AF_INET;
serverd.sin_port = htons(1024);
serverd.sin_addr.s_addr = inet_addr("127.0.0.1");



while (scelta !=5)//qui si entra nel while per scegliere cosa fare
{



printf ("Aspetto il codice del menu principale.\n");


FullRead(conn_fd,(char *)&scelta, sizeof(scelta));

printf("Messaggio Arrivato: %d \n", scelta);

switch(scelta)
{
case 1:
{
//case 1 permettiamo al client di visualizzare tutti gli appelli contenuti nella cartella del servers,il servers mostra soltanto i file con estensione .txt(ovvero gli appelli)
printf("LISTA DEGLI APPELLI:...\n");
DIR *dp;           
  int rv,rv1,stop_received,fscelta;       
   struct dirent *ep;   
 char buffer3[300],buffert[1024]; 
FILE *l=fopen("temp2","w");   //temp2 è il file che conterra la lista degli appelli 
            dp = opendir ("./");//la opendir punta alla cartella che contiene il file .c del servers
            if (dp != NULL){
                while (ep = readdir(dp)){
const size_t len = strlen(ep->d_name);
             if (strcmp(ep->d_name, ".") == 0
               || strcmp(ep->d_name, "..")==0 || strcmp(ep->d_name+len - 4, ".txt") != 0 )
               continue;
//carichiamo tutti i nomi in un buffer
               strcpy(buffer3,ep->d_name);
strcat(buffer3,"\n");
//qui con fwrite scriviamo sul file i nomi degli appelli presenti nella cartella del serverd
fwrite(buffer3, strlen(buffer3),sizeof(char),l);
	memset( buffer3, 0, sizeof( buffer3 ) );
            
                }

                (void) closedir(dp);fclose(l);
            }else
                perror ("impossibile aprire la directory\n");
//ora con un buffer inviamo il contenuto del file temp2 al clients che visualizza i nomi degli appelli
fscelta=open("temp2",O_RDONLY);
                if(fscelta<0)
         {
               fprintf(stderr,"Errore nella open(): %s\\ \n",strerror(errno));
               break;}   

while ((nread3=read(fscelta, buffert,sizeof(buffert))) !=0)
{
        write(conn_fd, buffert, nread3);
        
}
close(fscelta);
memset( buffert, 0, sizeof( buffert ) );


}break;


case 2:
{
//nel cse due permettiamo al clients di visualizzare il contenuto di un appello trmite un buffer
char nomefile[50];
write(conn_fd,"\nPREGO INSERIRE IL NOME DELL'APPELLO:",strlen("PREGO INSERIRE IL NOME DELL'APPELLO:\n"));			
          recv(conn_fd,nomefile,50,0);			

puts(nomefile);

int fsceltafile,nread2;
char buffer2[1024];

fsceltafile=open(nomefile,O_RDONLY);
                if(fsceltafile<0)
         {
               fprintf(stderr,"Errore nella open(): %s\\ \n",strerror(errno));
               break;}   

while ((nread2=read(fsceltafile, buffer2,sizeof(buffer2))) !=0)
{
        write(conn_fd, buffer2, nread2);
}
close(fsceltafile);
memset(buffer2, 0, sizeof(buffer2));
memset(nomefile, 0, sizeof(nomefile));
}break;



case 3:
{
//nel case 3 il clients puo modificare con semplicità nome/cognome/voto di un esame ricondando nel momento di sotituire una stringa di immettere al finaco del nome/cognome/voto anche le ultime tre cifre della matricola esempio stringa da sostituire=mario.320, nuova stringa carlo
char buffer2[1024];
char nomefile2[50];
//varibili dedicate a caricare le infomazioni sull'ultima modifica del file
char data[80];
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo=localtime(&rawtime);

char *ip = inet_ntoa(client.sin_addr);//qui conosciamo l'ip del cliuent che sta effettuando la modifica
write(conn_fd,"\nPREGO INSERIRE IL NOME DELL'APPELLO:",strlen("PREGO INSERIRE IL NOME DELL'APPELLO:\n"));				
          recv(conn_fd,nomefile2,50,0);			
puts(nomefile2);
write(conn_fd,"\nPREGO INSERIRE LA PAROLA DA SOSTITUIRE:",strlen("PREGO INSERIRE LA PAROLA DA SOSTITUIRE:\n"));
   recv(conn_fd,trova,30,0);	
write(conn_fd,"\nPREGO INSERIRE LA NUOVA PAROLA:",strlen("PREGO INSERIRE LA NUOVA PAROLA:\n"));
   recv(conn_fd,sostituisci,30,0);	
//per sostituire un nome/cognome/voto useremo duel file Input=l'appello da mkodifcare,output=l'appello modificato
    FILE *Input,*Output;

    Input = fopen(nomefile2, "r");
    Output = fopen(filetemp, "w");
 //il seguente codice effettua la modifica cercando l'occorrenza all'interno del file, per evitare che la sostituzione avvenga su tutte le stringe dello stesso tipo ES.(matricola:0124000322nome:mario,matricola:0123000323nome:mario), il serverd precedentemente attribuisce a ogni nome/cognome/voto le ultime tre cifre della matricola dello stundente in modod tale da creare una chiave univoca per identificare la stringa da trovare nel file

    if(NULL == Input)
    {
        printf("\nimpossibile aprire il file");
       break;
    }
 
    // per tutte le linee del file
    while(NULL != fgets(Buffer, 4095, Input))
    {
        char *Stop = NULL;
        char *Start = Buffer;
      //nel seguente while viene effettuata la ricerca e la sotituzione nel nuovo file terminando la nuova stringa con le ultime 3 cifre della matricola dello studente
        while(1)
        {
          
            
            Stop = strstr(Start, trova);
            if(NULL == Stop)
            {
                fwrite(Start, 1, strlen(Start), Output);
                break;
            }
        
            

            fwrite(Start, 1, Stop - Start, Output);
                       char cifre[4]; 
cifre[3]=trova[strlen(trova)-1]; 
cifre[2]=trova[strlen(trova)-2];
cifre[1]=trova[strlen(trova)-3]; 
cifre[0] = '.';
strcat(sostituisci,cifre);
  memset(cifre, 0, sizeof(cifre)); 
            fwrite(sostituisci, 1, strlen(sostituisci), Output);
            Start = Stop + strlen(trova);
    
     }
line++;



}
//nel codice seguente viene impresso sul file alla prima riga l'ultima modifica effettuata all'appello con data ora e ip del client che l'ha modificato
strftime(data,80,"ultima modifica in data %d-%m-%Y ora %H:%M da ",timeinfo);
strcat(data,ip);
puts(data);
rewind(Output);
fwrite(data, strlen(data),sizeof(char),Output);
memset(sostituisci, 0, sizeof(sostituisci)); 
memset(trova, 0, sizeof(trova));    
memset(data, 0, sizeof(data));
    fclose(Input);
    fclose(Output);
    remove(nomefile2);
    rename(filetemp, nomefile2);

//nel seguente codice viene effettuata la connect al serverd e l'invio dell'appello modificato

int serverd_fd;
serverd_fd = Socket(AF_INET,SOCK_STREAM,0);
if((connect(serverd_fd,(struct sockaddr *) &serverd,sizeof(struct sockaddr)) == -1))
	{
	printf("Il SERVERD é offline..impossibile inviare appello per l'archiviazione\n");
	}
	else {//il servers è online e ha risposto
	FullWrite(serverd_fd, &invio, sizeof(int));
//inviamo al serverd la lunghezza del nome del file e la stringa de inviare
uint32_t nomel = htonl(strlen(nomefile2));
write(serverd_fd, &nomel, sizeof nomel); 
write(serverd_fd, nomefile2, strlen(nomefile2)); 

//si apre l'appello modificato in lettura
FILE *fd = fopen(nomefile2,"r");
    if (fd < 0) {
      fprintf(stderr, "impossibile aprire '%s': %s\n", nomefile2, strerror(errno));
      exit(1);
    }

ssize_t bytes;
//si invia l'appello modficato al serverd
while ((bytes = fread(buffer2,sizeof(char), sizeof(buffer2),fd)) > 0)
{
   send(serverd_fd, buffer2, bytes, 0);
}
	
		printf("Trasmissione completata con successo\n\n");

	fclose(fd); 
close(serverd_fd);
	}

memset( nomefile2, '\0', sizeof( nomefile2 ) );





}break;

case 4:
{
//nel case 4 il clients puo modificare qualunque stringa del file 
char nomefile2[50];
char buffer2[1024];
char data[80];
//varibili dedicate a caricare le infomazioni sull'ultima modifica del file
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo=localtime(&rawtime);
char *ip = inet_ntoa(client.sin_addr);//ip del client che effettua la modifica

write(conn_fd,"\nPREGO INSERIRE IL NOME DELL'APPELLO:",strlen("PREGO INSERIRE IL NOME DELL'APPELLO:\n"));				
          recv(conn_fd,nomefile2,50,0);			
puts(nomefile2);
write(conn_fd,"\nPREGO INSERIRE RECORD DA MODIFICARE:",strlen("PREGO INSERIRE RECORD DA MODIFICARE::\n"));
   recv(conn_fd,trova,30,0);	
write(conn_fd,"\nPREGO INSERIRE IL NUOVO RECORD:",strlen("PREGO INSERIRE IL NUOVO RECORD:\n"));
   recv(conn_fd,sostituisci,30,0);	
//per sostituire un nome/cognome/voto useremo duel file Input=l'appello da mkodifcare,output=l'appello modificato
    FILE *Input,*Output;

    Input = fopen(nomefile2, "r");
    Output = fopen(filetemp, "w");
  //il seguente codice effettua la modifica cercando l'occorrenza all'interno del file

    if(NULL == Input)
    {
        printf("\nimpossibile aprire il file");
       break;
    }
 
 
    // per ogni linea
    while(NULL != fgets(Buffer, 4095, Input))
    {
        char *Stop = NULL;
        char *Start = Buffer;
      //nel seguente while viene effettuata la ricerca e la sotituzione nel nuovo file 
        while(1)
        {
          
       
            Stop = strstr(Start, trova);
            if(NULL == Stop)
            {
                fwrite(Start, 1, strlen(Start), Output);
                break;
            }

            fwrite(Start, 1, Stop - Start, Output);

            fwrite(sostituisci, 1, strlen(sostituisci), Output);

            Start = Stop + strlen(trova);
    
     }
line++;



}
//nel codice seguente viene impresso sul file alla prima riga l'ultima modifica effettuata all'appello con data ora e ip del client che l'ha modificato
strftime(data,80,"ultima modifica in data %d-%m-%Y ora %H:%M da ",timeinfo);
strcat(data,ip);
puts(data);
rewind(Output);
fwrite(data, strlen(data),sizeof(char),Output);

memset(sostituisci, 0, sizeof(sostituisci)); 
memset(trova, 0, sizeof(trova));    
memset(data, 0, sizeof(data));
    fclose(Input);
    fclose(Output);
    remove(nomefile2);
    rename(filetemp, nomefile2);
 //nel seguente codice viene effettuata la connect al serverd e l'invio dell'appello modificato

int serverd_fd;
int fd;
serverd_fd = Socket(AF_INET,SOCK_STREAM,0);
if((connect(serverd_fd,(struct sockaddr *) &serverd,sizeof(struct sockaddr)) == -1))
	{
	printf("Il SERVERD é offline..impossibile inviare appello per l'archiviazione\n");
	}
	else {

	FullWrite(serverd_fd, &invio, sizeof(int));
//inviamo al serverd la lunghezza del nome del file e la stringa de inviare
uint32_t nomel = htonl(strlen(nomefile2));
write(serverd_fd, &nomel, sizeof nomel); 
write(serverd_fd, nomefile2, strlen(nomefile2)); 

//si apre l'appello modificato in lettura
FILE *fd = fopen(nomefile2, "r");
    if (fd < 0) {
      fprintf(stderr, "impossibile aprire '%s': %s\n", nomefile2, strerror(errno));
      exit(1);
    }

ssize_t bytes;
//si invia l'appello modficato al serverd
while ((bytes = fread(buffer2,sizeof(char), sizeof(buffer2),fd)) > 0)
{
   send(serverd_fd, buffer2, bytes, 0);
}
	
	
		printf("Trasmissione completata con successo\n\n");

	fclose(fd); 
close(serverd_fd);
	}

memset( nomefile2, '\0', sizeof( nomefile2 ) );


}break;

case 0:
{
// nel case 0 terminaimo la connessione col servers
printf("IL CLIENT SEGRETERIA STUDENTI HA CHIUSO LA CONNESSIONE..\n");
close(conn_fd);//Chiudo la connessione
exit(0);


}break;




}
}
}
示例#9
0
/*
 * Copy data jumping over areas filled by '\0', so files automatically become sparse if possible.
 */
static bool CopyData(const char *source, int sd, const char *destination, int dd, char *buf, size_t buf_size)
{
    off_t n_read_total = 0;

    while (true)
    {
        ssize_t n_read = read(sd, buf, buf_size);

        if (n_read == -1)
        {
            if (errno == EINTR)
            {
                continue;
            }

            CfOut(OUTPUT_LEVEL_ERROR, "read", "Unable to read source file while doing %s to %s", source, destination);
            return false;
        }

        if (n_read == 0)
        {
            /*
             * As the tail of file may contain of bytes '\0' (and hence
             * lseek(2)ed on destination instead of being written), do a
             * ftruncate(2) here to ensure the whole file is written to the
             * disc.
             */
            if (ftruncate(dd, n_read_total) < 0)
            {
                CfOut(OUTPUT_LEVEL_ERROR, "ftruncate", "Copy failed (no space?) while doing %s to %s", source, destination);
                return false;
            }

            return true;
        }

        n_read_total += n_read;

        /* Copy/seek */

        void *cur = buf;
        void *end = buf + n_read;

        while (cur < end)
        {
            void *skip_span = MemSpan(cur, 0, end - cur);
            if (skip_span > cur)
            {
                if (lseek(dd, skip_span - cur, SEEK_CUR) < 0)
                {
                    CfOut(OUTPUT_LEVEL_ERROR, "lseek", "Copy failed (no space?) while doing %s to %s", source, destination);
                    return false;
                }

                cur = skip_span;
            }


            void *copy_span = MemSpanInverse(cur, 0, end - cur);
            if (copy_span > cur)
            {
                if (FullWrite(dd, cur, copy_span - cur) < 0)
                {
                    CfOut(OUTPUT_LEVEL_ERROR, "write", "Copy failed (no space?) while doing %s to %s", source, destination);
                    return false;
                }

                cur = copy_span;
            }
        }
    }
}
int modificaDatiAppello(int socket){
    int napp, i;
    long chose;
    char buffer[BUFF_SIZE],data[11],orario[11],*token;
    app_t appelliDaVisualizzare[100],app_mod;
    comm_t command = MOD_APP;
    struct tm data_t;
    
    do {
        printf("Appelli disponibili:\n");
        napp = visualizzaAppelli(socket, appelliDaVisualizzare);
        printf("Inserisci l'id dell'appello che vuoi aprire(0 - per terminare): ");
        fgets(buffer, sizeof(buffer), stdin);
        chose = atol(buffer);
        if (chose == 0) {
            break;
        }else{
            for (i = 0; i < napp; i++) {//cerca appello
                if (appelliDaVisualizzare[i].id == chose) {//appello valido
                    app_mod = appelliDaVisualizzare[i];
                    /*REGISTRO NUOVE INFORMAZIONI*/
                    strcpy(app_mod.matricolaProfessore, appelliDaVisualizzare[i].matricolaProfessore);//salvo la matricola di chi lo ha creato
                    /*prendo le informazioni dell'appello*/
                    printf("Dipartimeto: ");
                    if(fgets(app_mod.dipartimento, sizeof(app_mod.dipartimento), stdin) != NULL){
                        app_mod.dipartimento[strlen(app_mod.dipartimento)-1] = '\0';
                    }
                    
                    printf("Nome CDL: ");
                    if(fgets(app_mod.corsoDiLaurea, sizeof(app_mod.corsoDiLaurea), stdin) != NULL){
                        app_mod.corsoDiLaurea[strlen(app_mod.corsoDiLaurea)-1] = '\0';
                    }
                    printf("Nome esame: ");
                    if(fgets(app_mod.nomeEsame, sizeof(app_mod.nomeEsame), stdin)){
                        app_mod.nomeEsame[strlen(app_mod.nomeEsame) -1] = '\0';
                    }
                    
                    printf("Data appello(gg/mm/yyyy): ");
                    if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
                        sscanf(buffer, "%10s",data);
                    }
                    data_t.tm_mday = atoi((token = strtok(data, "-/")));//estrae il giorno
                    data_t.tm_mon = atoi((token = strtok(NULL, "-/")));//estrae il mese
                    data_t.tm_year = atoi((token = strtok(NULL, "-/"))) - 1900;//estrae l'anno
                    
                    printf("Orario(hh:mm): ");
                    if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
                        sscanf(buffer, "%5s",orario);
                    }
                    data_t.tm_hour = atoi((token = strtok(orario, ":"))) -1;//estrae l'ora
                    data_t.tm_min = atoi((token = strtok(NULL, ":")));//estrae i minuti
                    data_t.tm_sec = 0;
                    data_t.tm_isdst = 0;
                    app_mod.data = mktime(&data_t);
                    
                    app_mod.stato = appelliDaVisualizzare[i].stato;
                    /*Fine inserimento informazioni*/
                    write(socket, &command, sizeof(comm_t));//invio comando MOD_APP
                    FullWrite(socket, &app_mod, sizeof(app_t));//invio appello da modificare
                    read(socket, &command, sizeof(comm_t));//ricevo esito fopen
                    if (command == FILE_ERR) {
                        printf("Impossibile ,accesso negato\n");
                        return 0;
                    }
                    read(socket, &command, sizeof(comm_t));//leggo esito operazione
                    switch (command) {
                        case NOT_EXIST:
                            printf("Appello inesistente\n");
                            return 0;
                            break;
                        case SUCCESS:
                            printf("Appello modificato!\n");
                            return 1;
                            break;
                        default:
                            printf("Qualcosa è andato storto");
                            return 0;
                            break;
                    }
                }//
            }//fine for
            //arrivati qui l'id inserito non è valido
            printf("L'id inserito non e' valido,riprova\n$-segreteriaStudenti(0 - per terminare): ");
            fgets(buffer, sizeof(buffer), stdin);
            chose = atol(buffer);
        }
    } while (chose != 0);
    
    return -1;
}
int modificaDatiEsame(int fd){
    comm_t command= MOD_EX;
    app_t appelli[100];
    exam_t esami[100], esame;
    mat_t matricola;
    char buffer[BUFF_SIZE];
    int napp,nexa, i, j;
    long chose;
    
        printf("Appelli disponibili:\n");
        napp = visualizzaAppelli(fd, appelli);
        printf("Inserisci l'id dell'appello che vuoi aprire(0 - per terminare): ");
        fgets(buffer, sizeof(buffer), stdin);
        chose = atol(buffer);
        if (chose > 0) {
            for (i = 0; i < napp; i++) {//controlla se l'id e valido
                if (appelli[i].id == chose) {//id appello valido
                    nexa = visualizzaEsami(fd, chose, esami);//li salva nell'array
                    printf("Inserisci la matricola dell'esame da modificare: ");
                    fgets(buffer, sizeof(buffer), stdin);
                    sscanf(buffer, "%10s",matricola);
                    for (j = 0; j<nexa; j++) {
                        if (!strcmp(esami[j].matricola, matricola)) {//se la matricola è valida
                            /*Prendo informazioni esame*/
                            esame.id = chose;
                            printf("Nome studente: ");
                            fgets(esame.nome, 31, stdin);
                            esame.nome[strlen(esame.nome) - 1] = '\0';
                            printf("Cognome: ");
                            fgets(esame.cognome, 31, stdin);
                            esame.cognome[strlen(esame.cognome) - 1] = '\0';
                            printf("Matricola: ");
                            fgets(buffer, sizeof(buffer), stdin);
                            sscanf(buffer, "%10s",esame.matricola);
                            printf("Voto: ");
                            fgets(buffer, sizeof(buffer), stdin);
                            esame.voto = atoi(buffer);
                            
                            write(fd, &command, sizeof(comm_t));//invio comando MOD_EX
                            read(fd, &command, sizeof(comm_t));//leggo esito fopen
                            if (command == FILE_ERR) {
                                printf("Impossibile, accesso negato\n");
                                return 0;
                            }
                            FullWrite(fd, &esame, sizeof(exam_t));//invio esame modificato
                            read(fd, &command, sizeof(comm_t));//legge esito operazione
                            switch (command) {
                                case SUCCESS:
                                    printf("Esame modificato\n");
                                    return 1;
                                    break;
                                case FAIL:
                                default:
                                    printf("Qualcosa è andato storto\n");
                                    return 0;
                                    break;
                            }
                        }
                    }//arrivati qui matricola non valida
                    printf("Matricola non valida\n");
                    return 0;
                }
            }//arrivati qui id non valido
            printf("Id esame non valido");
            return 0;
        }//0 o < 0
    printf("Annullato\n");
    return 0;
}
int registraEsame(int fd,user_t *connected,int servFd){
    int n;
    size_t nread;
    FILE *fp,*fpAppelli;
    comm_t command = FAIL,response;
    exam_t *daRegistrare;
    app_t tmp;
    
    read(fd, &n, sizeof(int));//leggo quanti esami devo registrare
    daRegistrare = malloc(sizeof(exam_t) * (n+1));
    FullRead(fd, daRegistrare, sizeof(exam_t) * n);//memorizzo gli esami ricevuti
    if ((fp = fopen("esami.dat", "ab+")) == NULL) {
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito negativo
        perror("Errore apertura file: esami.dat");
        return 0;
    }
    /**DEVO CONTROLLARE SE L'APPELLO E CHIUSO*/
    if ((fpAppelli = fopen("appelli.dat", "rb")) == NULL) {
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito negativo
        perror("appelli.dat");
        return 0;
    }
    command = SUCCESS;
    write(fd, &command, sizeof(comm_t));//invio esito positio per i file
    while (1 == (nread = fread(&tmp, sizeof(app_t), 1, fpAppelli))) {//cerco appello
        if (daRegistrare[0].id == tmp.id) {//se ho trovato l'appello
            if (tmp.stato) {//se è aperto
                fwrite(daRegistrare, sizeof(exam_t), n, fp);//scrivo nel file
                command = SUCCESS;
                write(fd, &command, sizeof(comm_t));//invio esito positivo
                fclose(fp);
                /*Invio tutto al serverS*/
                command = REC;
                write(servFd, &command, sizeof(comm_t));//invio comando per registrare
                write(servFd, &n, sizeof(int));//invio il numero di esami da regisrare
                FullWrite(servFd, daRegistrare, sizeof(exam_t) * n);//invio array con gli esami da registrare
                read(servFd, &response, sizeof(comm_t));//leggo esito fopen
                free(daRegistrare);
                if (response == FILE_ERR) {
                    printf("ServerS non riesce ad aprire il file\n");
                    return 0;
                }
                read(servFd, &response, sizeof(comm_t));//leggo esito finale
                switch (response) {
                    case SUCCESS:
                        return 1;
                        break;
                    case CLOSE_APP:
                        printf("Impossibile regigistrare: appello chiuso\n");
                        return 0;
                    case FAIL:
                    default:
                        printf("Qualcosa è andato storto\n");
                        return 0;
                        break;
                }
                /*Fine gestione serverS*/
            }else{//è chiuso
                fclose(fp);
                free(daRegistrare);
                command = CLOSE_APP;
                write(fd, &command, sizeof(comm_t));//invio esito negativo
                return 0;
            }
        }
    }//appello non trovato se arrivati a questo punto
    command = NOT_EXIST;
    write(fd, &command, sizeof(comm_t));//invio esito negativo
    fclose(fpAppelli);
    fclose(fp);
    free(daRegistrare);
    return 0;
}