C program over-writing file contents in if statement -


i have c program trying record called "avalanche size". criteria recording if "delta_energy" generated program less equal 0 can increment avalanche size "*avalanche_size = *avalanche_size + 1;" , if delta_energy not less equal 0 continues running loop without incrementing avalanche size.

so want write delta energy when avalanche size incremented (not otherwise) file called delta_energies_gsa shown in code below.

but find happen if put fprintf statement inside if{ } avalanche size incremented sure, everytime 1 iteration, over-writes entries in file. in end end file containing delta energies 1 of iterations. if take fprintf statemenet , put outside bracket, records gives me delta energies when avalanche size not incremented , don't want those.

i thought doing maybe condition "if avalanche size bigger previous avalanche size fprintf delta energy" ... i'm not sure how since avalanche size integer not vector..

any appreciated! thank you

for (k = 0; k < n_nodes; k++)      {        if (delta_energy <= 0.0)         {             stored_state[i] = new_state;             *avalanche_size = *avalanche_size + 1;             printf("\n\n k = %d: ",k);             printf("\n\n delta energy gsa %d avalanche size:%f", *avalanche_size, delta_energy);              fprintf(delta_energies_gsa,"\n %d\t %d\t %f \n",k, *avalanche_size, delta_energy);          } 

i haven't shown full code because large function of large program. have been careful when open , close file. file opened right @ beginning of function after have declared variables. , close file right before function ends.

this how file opened:

{     double  d_energy, q_a_minus_1, one_over_q_a_minus_1, prob_term;     neighbor_inf    *np;  extern  int generate_new_state();  file *delta_energies_gsa;   delta_energies_gsa = fopen("delta_energies_gsa.dat", "w"); if (delta_energies_gsa == null)  {     printf("i couldn't open delta_energies_gsa.dat writing.\n");     exit(0); } 

right after declaring variables , closed before function ends:

    fclose(delta_energies_gsa); return(stored_state);  }    /* end recover_stored_patterns_gsa() */ 

the fprintf() want do, append string file, don't see wrong here code if fopen() outside loop (in case use "w+" fopen, append) , there aren't seek 0.

edit wrong, not "w+" "a" append (and if don't need read file).

the wrong behavior must investigate "why fprintf replace whole file". try simple test.

#include <stdio.h>  int main(int argc, char **argv) {     file *f = fopen("test", "w");     if (f) {             int i;             (i=0; i<100; i++) {                     if (i % 3)                             fprintf(f, "%d\n", i);              }             fclose(f);     }     return 0; } 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -