c - Iterating over multiple file objects -


i iterate on list/array of file objects: file_x,file_y,file_z,..., calling function on each file object, in c.

question

how can create function take (i) file object, , (ii) string arguments function , write string file object. for loop execute function on list/array of file objects.

void file_write(file_object, string_to_write){    fprintf(file_object, "%s\n", string_to_write); } 

research

i have searched google, watched parts of several youtube tutorials , searched relevant questions on so, following best achieve. advice on how better answer above question, ideal function, appreciated.

file *file_x, *file_y, *file_z, *file_vx, *file_vy  file_x  = fopen("./data/x.dat","w");  file_y  = fopen("./data/y.dat","w");  file_z  = fopen("./data/z.dat","w");  file_vx = fopen("./data/vx.dat","w");  file_vy = fopen("./vy.dat","w");   fprintf(file_x,  "#x(t) coordinates\n#time (t)\n"); fprintf(file_y,  "#y(t) coordinates\n#time (t)\n"); fprintf(file_z,  "#z(t) coordinates\n#time (t)\n"); fprintf(file_vx, "#x(t) velocities\n#time (t)\n"); fprintf(file_vy, "#y(t) velocities\n#time (t)\n");  fclose(file_x); fclose(file_y); fclose(file_z); fclose(file_vx); fclose(file_vy); 

you declare single file pointer , then,you can declare 2 arrays,one file names,and 1 data written them.make loop , iterate :

int main(void) {     file *file_x;      const char *dirs[] = { "./data/x.dat",                            "./data/y.dat",                            "./data/z.dat",                            "./data/vx.dat",                            "./vy.dat"                          };      const char *data[] = { "#x(t) coordinates\n#time (t)\n",                            "#y(t) coordinates\n#time (t)\n",                            "#z(t) coordinates\n#time (t)\n",                            "#x(t) velocities\n#time (t)\n",                            "#y(t) velocities\n#time (t)\n",                          };      for( int n = 0 ; n < 5 ; n++ )     {         file_x = fopen(dirs[n],"w");          if ( !file_x )         {             perror(dirs[n]);             exit(exit_failure);         }         fprintf(file_x , "%s" , data[n]);          fclose(file_x);     }     return 0; } 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -