65 lines
1.4 KiB
C++
65 lines
1.4 KiB
C++
/*
|
|
Nome: Mario
|
|
Cognome: Montanari
|
|
Classe: 3AIN
|
|
Data: 13/05/2025
|
|
|
|
Converti un file di testo in un file binario e viceversa:
|
|
1) Numeri interi (uno per ogni riga nel file di testo);
|
|
2) Numeri float (uno per ogni riga nel file edi testo);
|
|
3) Stringhe lunghe 20 (una per ogni riga nel file di testo);
|
|
4) Struct:
|
|
- Numeri complessi (uno per ogni riga nel file di testo);
|
|
- Libro: titolo, prezzo, nPagine.
|
|
*/
|
|
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
typedef struct {
|
|
char titolo[20+1];
|
|
float prezzo;
|
|
int nPagine;
|
|
} Libro;
|
|
|
|
int main(void) {
|
|
const char * fileNameIn = "libri.txt";
|
|
const char * fileNameOut = "libri.bin";
|
|
|
|
FILE * fileIn = fopen(fileNameIn, "rt");
|
|
|
|
if (fileIn != NULL) {
|
|
FILE * fileOut = fopen(fileNameOut, "wb");
|
|
|
|
if (fileOut != NULL) {
|
|
Libro libro;
|
|
|
|
char titolo[20+1];
|
|
float prezzo;
|
|
int nPagine;
|
|
|
|
while (fscanf(fileIn, "%[^\t]\t%f\t%d", titolo, &prezzo, &nPagine) == 3) {
|
|
strncpy(libro.titolo, titolo, 20);
|
|
libro.titolo[20] = '\0';
|
|
libro.prezzo = prezzo;
|
|
libro.nPagine = nPagine;
|
|
|
|
fwrite(&libro, sizeof(Libro), 1, fileOut);
|
|
cout << "Titolo: " << titolo << endl <<
|
|
"Prezzo: " << prezzo << endl <<
|
|
"Numero di pagine: " << nPagine << endl << endl;
|
|
}
|
|
|
|
fclose(fileOut);
|
|
} else {
|
|
perror("Error (destination)");
|
|
}
|
|
|
|
fclose(fileIn);
|
|
} else {
|
|
perror("Error (source)");
|
|
}
|
|
|
|
return 0;
|
|
} |