In: Computer Science
Array/File Functions
Write a function to accept three arguments:
The name of a file, a pointer to an int array, and the size of
the array. The
function should open the specified file in binary mode, write the
contents of the
array to the file, and then close the file.
Write another function to accept three arguments:
The name of a file, a pointer 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:
Function to write an array to a file, and then read the data from
the same file.
An array values shall be created, write to a file, and after that
data are read from
the file, and display the array’s contents on the screen.
Notes:
The filename parameter is the name of the file,
The array parameter is a pointer to the array, and
The size parameter is the number of elements in the array (size
of the array)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
//function to write the array to a file in binary mode
void binaryWrite(char *fname, int *ptr, int size);
//function to read from file into the array
void binaryRead(char *fname, int *ptr, int size);
int main(void) {
//declare an array and initialize with some elements
int arr[] = { 1,2,3,4,5,6 };
//using different array retArray while reading from bianry file , jsut to show that we are getting actutal result from the binary file
int *retArray=(int*)malloc(sizeof(sizeof(arr) / sizeof(int)));
int i;
printf("Content of array to write in binary mode to a file: \n");
for (i = 0; i < sizeof(arr) / sizeof(int); i++)
{
printf("%d ", arr[i]);
}
printf("\n");
binaryWrite("binaryWrite.dat", arr, sizeof(arr) / sizeof(int));
binaryRead("binaryWrite.dat", retArray, sizeof(arr) / sizeof(int));
//print read array
printf("Array after reading binary file\n");
binaryWrite("binaryWrite.dat", arr, sizeof(arr) / sizeof(int));
for (i = 0; i < sizeof(arr) / sizeof(int); i++)
{
printf("%d ", retArray[i]);
}
printf("\n");
return 0;
}
//function to write the array to a file in binary mode
void binaryWrite(char *fname, int *ptr, int size)
{
//open file in binary mode
FILE *fp;
fp = fopen(fname, "wb");
if (fp == NULL)
{
printf("Not able to open file %s for writing in binary mode\n", fname);
return;
}
fwrite(ptr, sizeof(int), size, fp);
fclose(fp);
}
//function to read from file into the array
void binaryRead(char *fname, int *ptr, int size)
{
//open file in binary mode
FILE *fp;
fp = fopen(fname, "rb");
if (fp == NULL)
{
printf("Not able to open file %s for reading in binary mode\n", fname);
return;
}
fread(ptr, sizeof(int), size, fp);
fclose(fp);
}
/*Output
./main
Content of array to write in binary mode to a file:
1 2 3 4 5 6
Array after reading binary file
1 2 3 4 5 6
*/
//Since programming language is not given , I am taking it as C , you can also execute this code in C++