I have to read a file, allocate an array of size k and store the k largest numbers in the array. I know how to scan and read the file and sort it but I don't know how to link them together. I will be really glad if someone could help me out with this issue!
I have tried to strlen, sizeof, counting loops of fscanf but none of them worked. The part with ??? is where I don know what to put. Generally I would put a amount of elements but in this case amount of elements in the file is unknown.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int main(int argc, char *argv[])//
{
FILE *iFile;
int k = atoi(argv[1]);//convert strings into int
int i = 0, j = 0, n = 0, temp = 0;
int *arr = (int *)malloc(k * sizeof(int));//allocate size k in an array
iFile = fopen("a.txt", "r");
if (iFile == NULL)
return -1;
while (feof(iFile) <= 0)
{
fscanf(iFile, "%d", arr);
//find number of elements since I have to compare all the numbers with each other
}
//reverse
for (i = 0; i < ??? - 1; i++) //Loop for descending ordering
{
for (j = 1; j <= ??? - 1; j++) //Loop for comparing other values
{
if (arr[j] < arr[i]) //Comparing other array elements
{
temp = arr[i]; //Using temporary variable for storing last temp
arr[i] = arr[j]; //replacing temp
arr[j] = temp; //storing last temp
}
}
}
for (i = 0; i < k; i++) //Loop for printing array
data after sorting
{
printf("%d\n", arr[i]); //Printing data
}
free(arr);
fclose(iFile);
return 0;
}