Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!dimacs.rutgers.edu!bcm!shell!shell!rjohnson From: rjohnson@shell.com (Roy Johnson) Newsgroups: comp.lang.c Subject: Re: Creating files with variable suffixes at run time Message-ID: Date: 17 Apr 91 15:51:25 GMT References: <1991Apr12.103621.8907@umiami.ir.miami.edu> <22418@yunexus.YorkU.CA> Sender: usenet@shell.shell.com (USENET News System) Organization: Shell Development Company, Bellaire Research Center, Houston, TX Lines: 43 In-Reply-To: racine@yunexus.yorku.ca's message of 16 Apr 1991 14:20:45 GMT 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