Imtiaz Raqib Imtiaz Raqib - 1 year ago 65
C Question

Write to separate files with different file names

This is what I am trying to achieve:

Assume the user inputs are:

Generating random instances ...

Enter the circuit board size MAX_X MAX_Y: 100 200

Enter the number of points NUM_PT: 10

Enter the number of random instances to be generated: 7

your program will generate in total 7 instances, written into 7
separate files "instance10_j.txt", for j = 1, 2, 3, ... Each
instance has the rectangular area [0 ; 100] X [0 ; 200], and has 10
points. The coordinates of a point is generated uniformly randomly
within the rectangular area. And your program makes sure there are no
duplicate points within each instance. If it is impossible for your
program to generate these files, prints out what an error is and quits.
All these files are saved in the current directory executing the
command, and your program prints to the screen:

instance10_1.txt generated

instance10_2.txt generated

instance10_3.txt generated

instance10_4.txt generated

instance10_5.txt generated

instance10_6.txt generated

instance10_7.txt generated ... done!

This is what I have done so far:

int writetofile(max_X, max_Y, numpt, random_inst);
int main(int argc, char *argv[])


FILE *fp;

int max_x, max_y, num_pt, rand_inst;
int *x_coordinate, *y_coordinate;

int inputfile = 0, outputfile = 0;
int i;

if (argc == 1)
/* to generate random instances, accepting parameters from stdin */
printf("Generating random instances...");
printf("Enter the circuit board size MAX_X MAX_Y: ");
scanf("%d %d", &max_x, &max_y);
printf("Enter the number of points NUM_PT: ");
scanf("%d", &num_pt);
printf("Enter the number of random instances to be generated: ");
scanf("%d", &rand_inst);
return 1;

int writetofile(max_X, max_Y, numpt, random_inst)


FILE *fp;
int i;

for (i = 1; i <= random_inst; i++)
fp = fopen(File with name instance[num_pt]_[rand_inst], "w");

fprintf(fp, "#%s\n", argv[inputfile]);
fprintf(fp, "#area [0, MAX_X] x [0, MAX_Y]\n");
fprintf(fp, "%d\t%d\n", max_x, max_y);
fprintf(fp, "#number of points NUM_PT\n");
fprintf(fp, "%d\n", num_pt);
fprintf(fp, "#coordinates\n");
for (i = 0; i < num_pt; i++)
fprintf(fp, "%d\t%d\n", x_coordinate[i], y_coordinate[i]);
fprintf(fp, "#end of instance\n");

I need to create random instances with no duplication but more importantly I should write them to separate files

My difficulty is in opening a file which would be named as
, which I think should be incorporated in the for loop.

I am using Ubuntu terminal to access my lab computer via ssh.

Language: c99 ; Compiler: gcc

Answer Source

Just like Kaylum mentioned.

char name[MAX_LEN];

/* Incorporate this into your for loop */

snprintf(name, MAX_LEN, "instance%d_%d.txt", num_pt, random_inst);
fopen(name, "w");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download