c - How to read a file and simultaneously fill an array -


in c program i'm writing have read values text file , put them in array later use.

i don't code (snippet shown below) because 2 while loops, first count number of values, create array big value, , lastly read file again, filling array.

also, in first loop, use variable x because fscanf() requires it, never use later in code , i'd avoid @ if possible.

int x, n=0, sum=0; fp=fopen("data.txt", "r");  while(fscanf(fp,"%d\n",&x)!=eof){     n++; }  rewind(fp); int v[n];  while(fscanf(fp,"%d\n",&v[i])!=eof){     sum+=v[i];     i++; } 

so, advice on how can improve code? figured kinda "fix" declaring array big "enough" @ beginning , filling needed. don't know in advance how many values have work with, decided trash out method.

this 1 scenario dynamic memory allocation can come handy. can follow general procedure described below

  1. define pointer.
  2. open file fopen() , read first element file fscanf(). error check should taken care, also.
  3. if read successful, allocate memory dynamically malloc() pointer , copy value.
  4. read next element.

    4.1. if read successful

    • if read successful, re-allocate memory realloc() 1 more new element size.

    • copy last read value newly allocated memory.

    4.2. if read id failure, check eof , stop reading.

  5. continue step 4.

also, please keep in mind, memory have allocate using dynamic memory allocation, needs free()d also.


as note, referring comment of mr. @ szczurcio, not optimized effort, because, you've re-allocte memory in each successful read. minimize impact of dynamic memory allocation, can decide on threshold value use allocate memory , then, when exhausted, double amount of previous value. way, allocation happen in chunk , allocation overhead in each read cycle can avoided.


Comments