【问题标题】:Write to separate files with different file names写入具有不同文件名的单独文件
【发布时间】:2017-02-17 19:40:48
【问题描述】:

这就是我想要达到的目标:

假设用户输入是:

生成随机实例 ...

输入电路板尺寸MAX_X MAX_Y: 100 200

输入点数NUM_PT:10

输入要生成的随机实例数:7

您的程序将生成总共 7 个实例,写入 7 单独的文件“instance10_j.txt”,对于 j = 1, 2, 3, ... 每个 实例具有矩形区域 [0 ; 100] X [0 ; 200],并且有 10 点。一个点的坐标是均匀随机生成的 矩形区域内。你的程序确保没有 每个实例中的重复点。如果对您来说不可能 生成这些文件的程序,打印出错误是什么并退出。 所有这些文件都保存在当前目录中执行 命令,你的程序就会打印到屏幕上:

instance10_1.txt 生成

instance10_2.txt 生成

instance10_3.txt 生成

instance10_4.txt 生成

instance10_5.txt 生成

instance10_6.txt 生成

instance10_7.txt 生成...完成!

这是我目前所做的:

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 我必须打开格式为instance[num_pt]_[random_instances] 的文件,我不知道该怎么做。
  • 你的意思是你不知道如何形成文件名?如果是这样:char name[MAX_LEN]; snprintf(name, MAX_LEN, "instance_%d_%d.txt", num_pt, random_inst); fopen(name, "w");
  • @kaylum 所以我定义了变量name 然后用它来打开我的文件来写?因为我必须在每个文件中增加random instances,所以变量是否在for loop 中定义?
  • 您可以在循环内部或外部定义变量。重要的是 snprintf 在循环内,因为它形成了文件名。

标签: c c99


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    相关资源
    最近更新 更多