In: Computer Science
Write a program in c that reads the content from the file and stores each line in an int array in heap(using dynamic memory allocation).
For example, let the file has elements following (we do not know the size of files, it could be above 100,000 and contents of the file and make sure to convert file elements to int):
10067
26789
6789
3467
C Program:
#include <stdio.h>
int main(int argc, char **argv)
{
int n=0; //Variable that holds the number of elements in the
file
FILE *fptr; //File Pointer
int val; //For holding value
int *arr; //Pointer array
int i=0;
//Opening file for reading
fptr = fopen("C:\\Users\\P.MANUSHA\\Documents\\DMA\\DMA\\ip.txt",
"r");
//Counting number of elements in the file
while( fscanf(fptr, "%d", &val) == 1 )
{
//Incrementing number of elements
n = n + 1;
}
//Allocating Memory
arr = (int*)malloc(sizeof(int)*n);
fseek(fptr, 0, SEEK_SET);
//Opening file for reading and storing data in file
//fptr = fopen("ip.txt", "r");
//Counting number of elements in the file
while( fscanf(fptr, "%d", &val) == 1 )
{
//Storing in array
*(arr+i) = val;
//Incrementing array index
i = i + 1;
}
//Closing file
fclose(fptr);
//Printing array elements
printf("\nElements present in array: ");
//Iterating over array
for(i=0; i<n; i++)
{
printf(" %d ", *(arr+i));
}
//Releasing memory
free(arr);
printf("\n");
return 0;
}
__________________________________________________________________________________________________________________________
Sample Run: