Creating files with variable suffixes at run time

Roy Johnson rjohnson at shell.com
Thu Apr 18 01:51:25 AEST 1991


In article <22418 at yunexus.YorkU.CA> racine at yunexus.yorku.ca (Jeff Racine) writes:
>I would like to create separate files for each variable with names
>like foo1.dat, foo2.dat, and so forth. The problem is that the number
>of variables is variable, so I cannot hard code a number of files to
>be open. The solution can open a file, write data, close the file,
>open the next, write data, close the file etc. that is, the files do
>not have to be open simultaneously. I hope this description is
>sufficient.

>Has anyone done this successfully? If so would you kindly outline your
>solution? If not can someone see an easy way of doing this?

This is a job for one of my favorites: freopen()

int main(argc, argv)
  unsigned argc;
  char     *argv[];
{
  int numfiles, i;
  char filename[50];

  /* Read number of variables from argv[1] */
  if (sscanf(argv[1], "%d", &numfiles) != 1) {
    perror("scanf");
    exit(1);
  }

  for (i = 0; i < numfiles; ++i) {
    sprintf(filename, "foo%d.dat", i);
    if (freopen(filename, "w", stdout) != stdout) {
      perror("freopen");
      exit(1);
    }
    /* Write all your data to the foo#.dat here */
  }
  fclose(stdout);
  return 0;
}
--
=============== !You!can't!get!here!from!there!rjohnson ===============
Feel free to correct me, but don't preface your correction with "BZZT!"
Roy Johnson, Shell Development Company



More information about the Comp.lang.c mailing list