diff --git a/file/es8_binary.cpp b/file/es8_binary.cpp new file mode 100644 index 0000000..57505cc --- /dev/null +++ b/file/es8_binary.cpp @@ -0,0 +1,65 @@ +/* +AUTORE: Manuel Vichi 3^AIN +Esercizio 8 File Binari +*/ +#include +#include +using namespace std; +int convertBinaryIntegers(const char * textFile, const char * binaryFile, const size_t count) { + FILE* text = fopen(textFile,"r"); + FILE* binary = fopen(binaryFile,"wb"); + if (text == NULL || binary == NULL) { + perror("Errore durante l'apertura dei file"); + return -1; + } else { + char buffer[count]; + int array[count]; + size_t i = 0; + for (size_t i = 0; i < count; i++) { + array[i] = 0; + } + while (fgets(buffer,sizeof(buffer),text) && i < count) { + int numero; + if (sscanf(buffer, "%d", &numero) == 1) { + array[i] = numero; + i++; + } + } + fwrite(&array,sizeof(int),count,binary); + fclose(text); + fclose(binary); + return 0; + } + return -1; +} +int convertBinaryFloat(const char * textFile, const char * binaryFile, const size_t count) { + FILE* text = fopen(textFile,"r"); + FILE* binary = fopen(binaryFile,"wb"); + if (text == NULL || binary == NULL) { + perror("Errore durante l'apertura dei file"); + return -1; + } else { + char buffer[count]; + float array[count]; + size_t i = 0; + for (size_t i = 0; i < count; i++) { + array[i] = 0; + } + while (fgets(buffer,sizeof(buffer),text) && i < count) { + float numero; + if (sscanf(buffer, "%f", &numero) == 1) { + array[i] = numero; + i++; + } + } + fwrite(&array,sizeof(int),count,binary); + fclose(text); + fclose(binary); + return 0; + } + return -1; +} +int main(void) { + //return convertBinaryIntegers("test.txt","test.bin",20); + return convertBinaryFloat("test.txt","test.bin",20); +}