[comp.lang.c] Creating files with variable suffixes at run time

racine@yunexus.yorku.ca (Jeff Racine) (04/16/91)

Hi.

I have a program which creates a data file. The user (at run time)
enters the number of variables. When the program runs, it generates a
data file which contains (in column form) the first variable, some
`stuff' for the first variable, the second variable, some stuff for
the second, and so on. Currently this is all dumped to one `mega'
file.

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?

Thanks for your time and effort.


--------------------------------------------------------------------
Jeff Racine        
racine@nexus.yorku.ca   
racine@yunexus.UUCP

rjohnson@shell.com (Roy Johnson) (04/17/91)

In article <22418@yunexus.YorkU.CA> racine@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