/* Nome: Mario Cognome: Montanari */ #include #include #define DIM_NUM 10 using namespace std; void print10Numbers_1(FILE * file); void print10Numbers_2(FILE * file); void read10Numbers_1(FILE * file); void read10Numbers_2(FILE * file); int main(void) { // CREO UN FILE BINARIO e LO AGGIORNO FILE * file = fopen("print10Numbers.bin", "w+b"); // con "wb" avrei dovuto togliere ultime due funzioni perché non è possibile leggere if (file != NULL) { cout << "Primo metodo per stampare: " << setw(3); print10Numbers_1(file); cout << endl; // RIPORTO IL PUNTATORE DEL FILE ALL'INIZIO rewind(file); // fseek(file, 0, SEEK_SET); cout << "Secondo metodo per stampare: "; print10Numbers_2(file); cout << endl; // RIPORTO IL PUNTATORE DEL FILE ALL'INIZIO rewind(file); // fseek(file, 0, SEEK_SET); cout << "Primo metodo per leggere: " << setw(4); read10Numbers_1(file); cout << endl; // RIPORTO IL PUNTATORE DEL FILE ALL'INIZIO rewind(file); // fseek(file, 0, SEEK_SET); cout << "Secondo metodo per leggere: " << setw(2); read10Numbers_2(file); cout << endl; fclose(file); } else { perror("Error (source)"); } return 0; } // PRIMO METODO PER STAMPARE DEI NUMERI void print10Numbers_1(FILE * file) { int num; for (int i = 0; i < DIM_NUM; i++) { num = i; // Stampo i numeri su file fwrite(&num, sizeof(int), 1, file); // Stampo i numeri su schermo cout << num << " "; } } // SECONDO METODO PER STAMPARE DEI NUMERI void print10Numbers_2(FILE * file) { int num[DIM_NUM]; for (int i = 0; i < DIM_NUM; i++) { num[i] = i; } // MODI PER STAMPARE SUL FILE (SOLO PER IL SECONDO METODO) fwrite(num, sizeof(int), DIM_NUM, file); // fwrite(num, sizeof(*num), DIM_NUM, file); // fwrite(num, sizeof(num[0]), DIM_NUM, file); // Stampo i numeri su schermo for (int i = 0; i < DIM_NUM; i++) { cout << num[i] << " "; } } // PRIMO METODO PER LEGGERE DEI NUMERI void read10Numbers_1(FILE * file) { int num; while (fread(&num, sizeof(int), 1, file) == 1) { // Stampo i numeri su schermo cout << num << " "; } } // SECONDO METODO PER LEGGERE DEI NUMERI void read10Numbers_2(FILE * file) { int num[DIM_NUM]; // MODI PER LEGGERE IL FILE (SOLO PER IL SECONDO METODO) fread(num, sizeof(int), DIM_NUM, file); // fread(num, sizeof(*num), DIM_NUM, file); // fread(num, sizeof(num[0]), DIM_NUM, file); // Stampo i numeri su schermo for (int i = 0; i < DIM_NUM; i++) { cout << num[i] << " "; } }