Ole Gooner
Ole Gooner

Reputation: 567

File handling in C. More commands?

Say, I have a file that contains 100000 integers. Each integer is on a new line in the file. My task is to firstly store these integers in an array and then secondly, find the number of inversions possible in these 100000 numbers using the mergesort algorithm. The latter part which I've managed to do.

I've written the code to read each line and then store every single digit in a 2 Dimensional array. For instance say 54667 is on the first line and 67890 is on the second line

Then the code that I've written performs this

arr[i][j]=5 arr[i][j+1]=4 arr[i][j+2]=6........(and so on)
 arr[i+1][j]=6 arr[i+1][j+1]=7 arr[i+1][j+2]=8......

and then I have to reconstruct these integers by multiplying by suitable powers of 10, and store them in a 1 Dimensional array.

However, writing while writing this code I somehow was convinced that there has to be a simpler way to do this in C. As in, isn't there some function or command that makes this job easier?

Upvotes: 0

Views: 247

Answers (1)

cnicutar
cnicutar

Reputation: 182754

Yeah, just use fgets and strtol every line.

char line[LEN];
long array[NUM];
int i;

while (i < NUM && fgets(line, sizeof(line), stdin))
    array[i++] = strtol(line, NULL, 10);

Upvotes: 1

Related Questions