Write a function named arrayToFile. The function should accept three arguments:
ID: 3764262 • Letter: W
Question
Write a function named arrayToFile. The function should 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 named fileToArray. This function should 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 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.
Explanation / Answer
Program code:
#include "stdafx.h"
#include<iostream>
#include<stdio.h>
using namespace std;
void arrayToFile(FILE *,int *a,int size);//methods declaration
void fileTOArray(FILE *fileP,int *a, int size);
int main()
{
int counter;
const int size=5;
int a[size]={1,2,3,4,5};//static array declaration
FILE *fileP;
fileP=fopen("file.txt","wb");//binary write mode
arrayToFile(fileP,a, size);//calling method arrayToFile
fclose(fileP);
FILE *filep2;
filep2=fopen("file.txt","rb");//binary read mode
int b[5];
fileTOArray(filep2,b,size);//calling method fileTOArray
for(int i=0;i<5;i++)
{
printf("%d ",b[i]);
}
printf(" ");
system("pause");
return 0;
}
//method defintion of arrayToFile
void arrayToFile(FILE *fileP,int *a, int size)
{
fwrite(a,sizeof(int),size,fileP);
}
//method defintion of fileTOArray
void fileTOArray(FILE *fileP,int *a, int size)
{
fread(a,sizeof(int),size,fileP);
}
Sample output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.