1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void arrayToFile(string fileName, int *array, int sizeArray)
{
ofstream outputFile(fileName, ios::binary); // file opened in binary mode
outputFile.write(reinterpret_cast<char *>(array), sizeArray * sizeof(int)); //.write member accepts pointer to char as first argument
// so use reinterpret_cast when calling it
outputFile.close();
}
void fileToArray(string fileName, int *array, int sizeArray)
{
ifstream inputFile(fileName, ios::binary);
inputFile.read(reinterpret_cast<char *>(array), sizeArray * sizeof(int)); //.read member accepts pointer to char as first argument
// so use reinterpret_cast when calling it
inputFile.close();
}
int main()
{
const int arraySize = 5;
int array[arraySize] = {1, 2, 3, 4, 5};
int arrayToRead[arraySize];
//call arrayToFile function to write into file
cout << "Let's start to write on the file from the array\n";
arrayToFile("ziziMechant.dat", array, sizeof(array));
cout << "Done\n";
//call fileToArray to read from file
cout << "Let's read that file to the array\n";
fileToArray("ziziMechant.dat", arrayToRead, sizeof(arrayToRead));
cout << "Job done\n";
//display the array we just read
cout << "Let's display the array content\n";
for (int i = 0; i < arraySize; i++)
{
cout << arrayToRead[i] << ",";
}
cout << "\n";
return 0;
}
|