gpt4 book ai didi

c - 写入具有不同文件名的单独文件

转载 作者:行者123 更新时间:2023-11-30 16:56:20 25 4
gpt4 key购买 nike

这就是我想要实现的目标:

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 7separate files "instance10_j.txt", for j = 1, 2, 3, ... Eachinstance has the rectangular area [0 ; 100] X [0 ; 200], and has 10points. The coordinates of a point is generated uniformly randomlywithin the rectangular area. And your program makes sure there are noduplicate points within each instance. If it is impossible for yourprogram to generate these files, prints out what an error is and quits.All these files are saved in the current directory executing thecommand, 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!

这是我到目前为止所做的:

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;
}
/* MAIN FUNCTION CONTINUES FOR REMAINING WORK */
}

int writetofile(max_X, max_Y, numpt, random_inst)

{

FILE *fp;
int i;

for (i = 1; i <= random_inst; i++)
{
/* NEED HELP HERE */
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");
fclose(fp);

我需要创建不重复的随机实例,但更重要的是我应该将它们写入单独的文件

我的困难在于打开一个名为 instance[num_pt]_[random_instances] 的文件,我认为应该将其合并到 for 循环中。

我正在使用 Ubuntu 终端通过 ssh 访问我的实验室计算机。

语言:c99 ;编译器:gcc

最佳答案

就像Kaylum提到的那样。

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");

关于c - 写入具有不同文件名的单独文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com