84 lines
1.5 KiB
C++
84 lines
1.5 KiB
C++
/*
|
|
Nome: Mario
|
|
Cognome: Montanari
|
|
Classe: 3AIN
|
|
Data: 05/05/2025
|
|
|
|
Funzione di Bubble Sort che ordina direttamente su un file
|
|
*/
|
|
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
typedef struct {
|
|
int value;
|
|
} basetype;
|
|
|
|
void fbubbleSort(FILE * file);
|
|
void fprint(const char * filename);
|
|
|
|
int main(void) {
|
|
const char * filename = "data.bin";
|
|
|
|
FILE * file = fopen(filename, "r+b");
|
|
|
|
if (file != NULL) {
|
|
fbubbleSort(file);
|
|
fprint(filename);
|
|
|
|
fclose(file);
|
|
} else {
|
|
perror("Error");
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
void fbubbleSort(FILE * file) {
|
|
basetype arr[2];
|
|
|
|
fseek(file, 0, SEEK_END);
|
|
long n = ftell(file) / sizeof(basetype);
|
|
rewind(file);
|
|
|
|
for (int i = 0; i < n - 1; i++) {
|
|
for (int j = 0; j < n - i- 1; j++) {
|
|
fseek(file, j * sizeof(basetype), SEEK_SET);
|
|
if (fread(&arr, sizeof(basetype), 2, file) < 2) {
|
|
cout << "Errore di lettura." << endl;
|
|
return;
|
|
}
|
|
|
|
if (arr[0].value > arr[1].value) {
|
|
basetype temp = arr[0];
|
|
arr[0] = arr[1];
|
|
arr[1] = temp;
|
|
|
|
fseek(file, j * sizeof(basetype), SEEK_SET);
|
|
if (fwrite(&arr, sizeof(basetype), 2, file) < 2) {
|
|
cout << "Errore di scrittura." << endl;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void fprint(const char * filename) {
|
|
FILE * file = fopen(filename, "rb");
|
|
|
|
if (file != NULL) {
|
|
basetype temp;
|
|
|
|
while (fread(&temp, sizeof(basetype), 1, file) == 1) {
|
|
cout << temp.value << " ";
|
|
}
|
|
|
|
cout << endl;
|
|
|
|
fclose(file);
|
|
} else {
|
|
perror("Error");
|
|
}
|
|
} |