#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { setvbuf(stdout, 0, _IONBF, 0); FILE *f = fopen("pfseek.dat", "wb"); int i; for(i=0;i<5;i++) { printf("inserisci valore %d-esimo ", i); int x; scanf("%d", &x); fwrite(&x, sizeof(int),1,f); printf("\n"); } fclose(f); // r+b lettura e scrittura su file binario f = fopen("pfseek.dat", "r+b"); for(i=0; i<4; i++){ int j; int a; fseek(f, i*sizeof(int), SEEK_SET); fread(&a, sizeof(int), 1, f); for(j=i+1; j<5; j++) { int b; fseek(f, j*sizeof(int), SEEK_SET); fread(&b, sizeof(int), 1, f); printf("a=%d, b=%d \n", a, b); if (b<a) { int app = a; a = b; b = app; fseek(f, i*sizeof(int), SEEK_SET); fwrite(&a, sizeof(int), 1, f); fseek(f, j*sizeof(int), SEEK_SET); fwrite(&b, sizeof(int), 1, f); printf("scambio a=%d, b=%d \n", a, b); } } } fclose(f); f = fopen("pfseek.dat", "rb"); int y; // non si usa feof perché darebbe la dupplicazione dell'ultimo valore letto while(fread(&y, sizeof(int), 1, f) == 1) { printf("%d ", y); } fclose(f); return (EXIT_SUCCESS); }