In: Computer Science
C++
Goals:
Write a program that works with binary files.
Write a program that writes and reads arrays to and from binary files.
Gain further experience with functions.
Array/File Functions
Write a function named arrayToFile. The function should accept three arguments: the name of file, a pointer to an int array, and the size of the array. The function should open the specified file in binary made, write the contents into the array, and then close the file.
write another function named fileToArray. This function should accept three arguments: the name of a file, apointer to an int array, and the size of the array. The function should open the specified file in binary mode, read its contents into the array, and then close the file.
Write a complete program that demonstrates these functions by using the arrayTofile function to write an array to a file, and then using the fileToArray function to read the data from the same file. After the data are read from the file into the array, display the array's contents on the screen.
/*
* Please note that the compiler i used to comile the code is Visual
Studio Cummunity 2019.
* If you face any errors while compiling the code, please make
suitable adjustments like
* #include <iostream.h>
* #include <fstream.h>
* Avoiding the use of std::
* etc
*/
#include <iostream>
#include <fstream>
int arrayToFile(char* file, int* arr, int n)
{
std::ofstream fout(file, std::ios::binary);
if (fout.fail())
return 0;
fout.write((char*)arr, n * sizeof(arr[1]));
fout.close();
return 1;
}
int fileToArray(char* file, int* arr, int n)
{
std::ifstream fin(file, std::ios::binary);
if (fin.fail())
return 0;
fin.read((char*)arr, n * sizeof(arr[0]));
fin.close();
return 1;
}
int main()
{
int original[10] = { 8,1,44,13,11,13,22 };
// Writing the array to the file
arrayToFile((char*)"file.obb", original, 10);
int duplicate[10];
// Reading the contents already written to the
file
fileToArray((char*)"file.obb", duplicate, 10);
// Displaying Contents to the screen
for (int i = 0; i < 10; ++i)
{
std::cout << duplicate[i]
<< " ";
}
return 0;
}