1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
void addOwner()
{
proprietaire* proprio = (proprietaire*)malloc(sizeof(proprietaire));
if(proprio == NULL){
perror("L'allocation n'a pu etre réalisee\n");
exit(1);
}
int fd=open(PATH_FILE_OWNER, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
struct flock verrou;
verrou.l_type=F_WRLCK;
verrou.l_whence=verrou.l_start=verrou.l_len=0;
while((fcntl(fd, F_SETLK, &verrou) )== -1 && (errno == EACCES || errno == EAGAIN)){
sleep(5);
printf("Verrouiller\n");
}
int idDispo = FALSE,
id;
while(idDispo == FALSE)
{
cleanBuffer();
printf("Entrez un identifiant non utilise\n");
scanf("%d", &id);
printf("id: %d\n", id);
// verifie si l'id est utilisé
int trouve = FALSE, temp;
while((temp = read(fd, proprio, sizeof(proprietaire))) != 0 && trouve == FALSE)
{
// I have add this for verify the error, it is right ? (if yes I ll do every where :)
if(temp < 0){
printf("Boucle %d\n", temp);
perror("erreur");
printf("errno=%d\n", errno);
exit(1);
}
if(proprio->identifiant == id){
trouve = TRUE;
}
}
// si l'id est utilisé redemande un autre id et refait une recherche,
// sinon sort de la boucle et continue
if(trouve == TRUE){
printf("Identifiant deja utilise\n");
} else {
idDispo = TRUE;
}
}
// demande le reste des info et initialise la structure
proprio->identifiant = id;
printf("Entrez son nom:\n");
scanf("%s",proprio->nom);
printf("Entrez son prenom:\n");
scanf("%s",proprio->prenom);
printf("Entrez son adresse:\n");
scanf("%s",proprio->adresse);
proprio->nbVoiture = 0;
// test affichage
printf("Id : %d\n", proprio->identifiant);
printf("Nom: %s\n", proprio->nom);
printf("Prenom: %s\n", proprio->prenom);
printf("Adresse: %s\n", proprio->adresse);
printf("Nombre de voiture posseder: %d\n\n", proprio->nbVoiture);
// j'enregistrer le proprietaire
lseek(fd,0,SEEK_END);
write(fd, proprio , sizeof(proprio));
// je deverrouille
verrou.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &verrou) == -1){
perror("Impossible de deverouiller le record");
exit(1);
}
close(fd);
free(proprio);
} |
Partager