Assume that the lab03-data.dat file contains an array of int variables. Write a
ID: 3750317 • Letter: A
Question
Assume that the lab03-data.dat file contains an array of int variables. Write a C program to read this data file entirely into memory, then display the data using a loop To accomplish this, you must call each of the following functions exactly once: calloc) fopen (), fread), and fclose). In other words, allocate enough memory for this file (you can hard-code the number of bytes needed), then use only one call to fread) to read in exactly that number of bytes. Finally, display the data as follows: Data point Data point Data point # # # 0: 1: 2: Data point Data point Data point #183: #184: #185 : int-value> int-value>Explanation / Answer
int main(){
FILE *fin;//file pointer
//open the file
fin = fopen("lab03-data.dat", "r+");
int const TOTAL_ELEMENTS=25;
int num;
for(int i=0;i<TOTAL_ELEMENTS;i++)
{
num=i+100*i+20;
fwrite(&num, sizeof(int), 1, fin);
printf("%d ",i+100*i+20);
}
return (0);
}
-----------------------------------------------------------------------------------------------------------
/*
* File: main.c
* Author:
*
* Created on 19 September, 2018, 6:32 PM
*/
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(int argc, char** argv) {
FILE *fin;//file pointer
//open the file
fin = fopen("lab03-data.dat", "r+");
int const TOTAL_ELEMENTS=25;
int *array;//array of integers
long totalBytes=TOTAL_ELEMENTS*sizeof(int);
array = (int*) calloc(totalBytes, sizeof (int));//allocate enough bytes to store values in file
//if not enough memory
if (array == NULL)
return 1;
if(fin!=NULL)//if file opened properly
{
fread(array, sizeof (int), TOTAL_ELEMENTS, fin);//read the file
fclose(fin);
}
//printing the array
for(int i=0;i<TOTAL_ELEMENTS;i++)
printf("Data point # %d:%d ",i,*(array+i));
//free memory allocated
free(array);
return (EXIT_SUCCESS);
}
-----------------------------------------------------------------------------------------------
output
Data point # 0:20
Data point # 1:121
Data point # 2:222
Data point # 3:323
Data point # 4:424
Data point # 5:525
Data point # 6:626
Data point # 7:727
Data point # 8:828
Data point # 9:929
Data point # 10:1030
Data point # 11:1131
Data point # 12:1232
Data point # 13:1333
Data point # 14:1434
Data point # 15:1535
Data point # 16:1636
Data point # 17:1737
Data point # 18:1838
Data point # 19:1939
Data point # 20:2040
Data point # 21:2141
Data point # 22:2242
Data point # 23:2343
Data point # 24:2444
RUN SUCCESSFUL (total time: 126ms)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.