Soluzioni esercizi Homework 4

Esercizio 1

#include <stdio.h>
#include <stdlib.h>

typedef struct Studente {
  char Nome [20];
  char Cognome [20];
  char data_di_nascita [11];
  unsigned int Matricola;

} record_studente;


int copy_string(char* s1, char* s2, int index) {
  int i = 0;
  while (s1[index] != ';') {
    s2[i] = s1[index];
    i++;
    index++;
  }
  s2[i] = '\0';
  return index+2;
}

int read_line (record_studente* corrente, FILE* input){
  char* line = (char*) calloc(100, sizeof(char));
  int c;
  int i = 0;
  while (((c=fgetc(input)) != '\n') && (c!=EOF)){
    line[i] = c;
    i++;
  }
  if (i>0) {
    line[i-1] = '\0';
    i = copy_string (line, corrente->Nome, 0);
    i = copy_string (line, corrente->Cognome, i);
    i = copy_string (line, corrente->data_di_nascita, i);
    corrente->Matricola = atoi (line+i);
  } else return 0;
  return 1;
}


int scrivi_dati (char* file_input, char* file_output){
  FILE* input = fopen (file_input, "r");
  FILE* output = fopen (file_output, "wb+");
  unsigned matr;
  int fine = 1;
  if ((input == NULL) || (output == NULL))
    return -1;
  while (fine != 0){
    record_studente corrente;
    fine = read_line(&corrente, input);
    if (fine > 0){
      if ((fwrite(&corrente, sizeof(corrente), 1, output) != 1)){
        printf("fwrite == -1\n");
        return -1;
      }
    }
  }
  fclose (output);
  fclose (input);
  return 0;
}

Esercizio 2

int cancella_doppioni(char* file_binario){
  FILE* iofile = fopen (file_binario, "rwb+");
  if (iofile == NULL) return -1;
  record_studente rec;
  long nc = 0, precedente = 0, next_itr = 0, next = 0;
  
  while (fread(&rec, sizeof(rec), 1, iofile) == 1) {
    next += sizeof(rec);
    if (rec.Matricola != 0){
      record_studente current;
      precedente = next;
      next_itr = next;
      while (fread(&current, sizeof(current), 1, iofile) == 1){
        next_itr += sizeof(current);
        if (current.Matricola == rec.Matricola){
          fseek (iofile, precedente, SEEK_SET);
          current.Matricola = 0;
          fwrite(&current, sizeof(current), 1, iofile);
          nc++;
        }
        precedente = next_itr;
        fseek (iofile, next_itr, SEEK_SET);
      }
    }
    fseek (iofile, next, SEEK_SET);
  }
  fclose (iofile);
  return nc;
}

-- JulindaStefa - 04 Feb 2008


This topic: Programmazione1 > WebHome > Prog1PZ > HomeworksPZ0708 > Soluzioni5PZ0708
Topic revision: r1 - 2008-02-04 - JulindaStefa
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback