We need to make an integer array from a file such a way that the upper line of file would be size and the next line of numbers would be in an array having size of upper line integer value.
We read integers from the file. I am trying to solve by using a counter in a while loop that increments if we move to next line. odd number lines(1,3,5,7..) have only one integer which is size for an array and even number lines(2,4,6,8...) will have numbers intended to be in an array.
Now, when counter is odd(when 1) its looking on first line in file. This will determins the size of an array which numbers are in the 2nd line.
Example if a file has
3 //(line1) count=1(odd) -this case-> array size found is 3
5 6 2 //(line2) count=2(even) -this case-> array of size 3 is made
5 //(line4) count=3(odd) -this case-> array size found is 5
3 5 7 1 6 //(line4) count=4(even) -this case-> array of size 5 is made
3 will be used as a key to allocate the array of size 3 for [5 6 2]
then,
5 will be used as a key to allocate the array of size 3 for [3 5 7 1 6]
int main()
{
int count=1;
FILE* file = fopen("file.txt", "r");
int num ,i, element;
while (!feof (file) && num > 0){
if (count%2==0){
fscanf (file, "%d", &num);
}
else{
int *arr = (int *)malloc(num*(sizeof(int)));
fscanf (file, "%1d", &element);
arr[i] = element;
free(arr);
}
count++;
}
fclose (file);
return 0;
}
I don't know how should i use the (count) to find the number of line we are iterating in a file.