School-Coding-Cpp/sfusi/txt2bin.cpp

47 lines
948 B
C++

#include <iostream>
using namespace std;
typedef struct {
char cognome[100+1];
char nome[100+1];
int anno;
} Structure;
int main(void) {
const char * fileNameIn = "fileIn.txt";
const char * fileNameOut = "fileOut.bin";
FILE * fileIn = fopen(fileNameIn, "rt");
if (fileIn != NULL) {
FILE * fileOut = fopen(fileNameOut, "wb");
if (fileOut != NULL) {
Structure structure;
char cognome[100+1];
char nome[100+1];
int anno;
while (fscanf(fileIn, "%[^\t]\t%[^\t]\t%d", cognome, nome, &anno) == 3) {
strcpy(structure.cognome, cognome);
strcpy(structure.nome, nome);
structure.anno = anno;
fwrite(&structure, sizeof(structure), 1, fileOut);
cout << cognome << " " << nome << " " << anno;
}
fclose(fileOut);
} else {
perror("Error (destination)");
}
fclose(fileIn);
} else {
perror("Error (source)");
}
return 0;
}