Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function named arrayToFile. The function should accept three arguments:

ID: 3839424 • 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

#include<stdio.h>

void toFile(char *filename, int *array, int n){

   FILE *fp;
   int *p;

   fp = fopen(filename, "wb");
   if (fp == NULL){
       printf("File opening error ");
       return;
   }
   p = array;
   for (i=0; i<n; i++){
       fwrite(p, sizeof(int),1,fp);
       p++;
   }
   fclose(fp);
}

void toArray(char *filename, int *array, int n){

   FILE *fp;
   int *p;

   fp = fopen(filename, "rb");
   if (fp == NULL){
       printf("File opening error ");
       return;
   }
   p = array;
   for (i=0; i<n; i++){
       fread(p, sizeof(int),1,fp);
       p++;
   }
}

void main() {

   int a[5], b[5];
   char filename[20];

   filename = "Input.txt";
   for (int i = 0; i<5; i++)
        a[i] = i;
   toFile(filename,a,5);
   toArray(filename,b,5);
   for (int i = 0; i<5; i++)
        printf("%d ",b[i]);  
  
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote