How to keep track of last position of "i" when reading in different integers from multiple files into a 1dim-array?

Viewed 34

I want to read multiple integers into a 1 dimensional array from different files but how can I track at what position "i" stopped so I can continue saving from the position where "i" stopped? I am not allowed to have multiple files at a time opened and that's irritating me. I have read the rows and columns size of each file already and saved it.

len = rows * cols;
for(int i=0;i<len;i++) {
        fscanf(fp, "%d", &array[i]);
}

is a for loop the loop I have to go with or would an other loop be better? Maybe it's possible to use a pointer to track down the position where the loop stopped, something like this?

int i = 0;
    char c;
    do{
        fscanf(fp, "%d", &array[i]);
        i++;
        *cnt = i;
    }while((c=fgetc(fp)) != EOF);

but how do I set "i" to cnt when I call the function a second time?

1 Answers

I understand your question as: you read number from multiple files and put the into one array and you need to know the correct index in the array where the write would happen across all files.

You do not need to use pointer to do that, in a sense that the pointer is not required here (although this problem could be solved by using pointer). There are a few ways to achieve what you want:

1:

You could use a global variable to be the index in your array.

unsigned int index = 0

int main() {
    read_from_file_and_save(filename);
}

void read_from_file_and_save() {
    char c;
    do{
        fscanf(fp, "%d", &array[index]);
        index++;
    }while((c=fgetc(fp)) != EOF);
}

2:

Alternatively, you could use a static variable. Static variables are initialized only once in the whole lifetime of a program and so you could write:

void read_and_save() { 
   static unsigned int i = 0;
   char c;
   do{
       fscanf(fp, "%d", &array[i]);
       i++;
   }while((c=fgetc(fp)) != EOF);
}

It is guaranteed that the line:

static unsigned int i = 0;

is going to be executed only once, at the first call to the function.

Related