Advertisement
Guest User

Untitled

a guest
Mar 2nd, 2014
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct  {
  5. int ID;
  6. char Nome[25];
  7. }Studente;
  8.  
  9.  
  10. void Leggi(char *nomefile);
  11. void Inserisci(char *nomefile);
  12. void Cancella(char *nomefile);
  13.  
  14. int main()
  15. {
  16.     int i;
  17.  
  18.     for(i=0;i<2;i++)
  19.     Inserisci("Informazioni.dat");
  20.  
  21.     printf("\n");
  22.     Leggi("Informazioni.dat");
  23.     Cancella("Informazioni.dat");
  24.     printf("\n");
  25.     Leggi("Informazioni.dat");
  26.  
  27. return 0;
  28. }
  29.  
  30. void Inserisci(char *nomefile){
  31.  
  32.     FILE *pf;
  33.  
  34.     Studente *s;
  35.  
  36.     s =(Studente*)malloc(sizeof(Studente));
  37.  
  38.     if(s==NULL){
  39.         printf("Impossibile allocare memoria...");
  40.         exit (1);
  41.     }
  42.     pf = fopen(nomefile,"a+b");
  43.  
  44.     if(pf){
  45.  
  46.         printf("\nInserisci ID : ");
  47.         scanf("%d",&s->ID);
  48.         getchar();
  49.  
  50.         printf("Inserisci il nome : ");
  51.         gets(s->Nome);
  52.  
  53.         fwrite(s,sizeof( Studente),1,pf);
  54.  
  55.         fclose(pf);
  56.         free(s);
  57.  
  58.     }
  59. }
  60.  
  61. void Leggi(char *nomefile){
  62.  
  63.     FILE *pf;
  64.     Studente s;
  65.  
  66.     pf = fopen(nomefile,"r");
  67.     if(pf){
  68.         while(fread(&s,sizeof(Studente),1,pf)!=0){
  69.             printf("ID: %d\n",s.ID);
  70.             printf("Nome: %s\n",s.Nome);
  71.             printf("\n");
  72.        }
  73.         fclose(pf);
  74.     }
  75.     else{
  76.         printf("Erroe durante l'apertuta del file...");
  77.         exit(1);
  78.     }
  79.  
  80. }
  81.  
  82. void Cancella(char *nomefile){
  83.  
  84.     FILE *pf;
  85.  
  86.     int ID_Studente;
  87.     Studente s;
  88.     int trovato=0;
  89.  
  90.     pf = fopen(nomefile,"r+b");
  91.  
  92.     printf("Inserisci ID da cancellare :");
  93.     scanf("%d",&ID_Studente);
  94.  
  95.     while (!feof(pf) && trovato==0) // scorro tutto il file finchè non lo trovo
  96. {
  97.  
  98.     fread(&s,sizeof(Studente),1,pf);
  99.  
  100.  
  101.         if(s.ID == ID_Studente)
  102.             {
  103.                 printf("\nTrovato...");
  104.                 trovato=1;
  105.  
  106.             }
  107.  
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement