prev up next   top/contents search

comp.lang.c FAQ list · Question 19.28

Q: How can I call system when parameters (filenames, etc.) of the executed command aren't known until run time?

A: Just use sprintf (or perhaps strcpy and strcat) to build the command string in a buffer, then call system with that buffer. (Make sure the buffer is allocated with enough space; see also questions 7.2 and 12.21.)

Here is a contrived example suggesting how you might build a data file, then sort it (assuming the existence of a sort utility, and Unix- or MS-DOS-style input/output redirection):

	char *datafile = "file.dat";
	char *sortedfile = "file.sort";
	char cmdbuf[50];
	FILE *fp = fopen(datafile, "w");

	/* ...write to fp to build data file... */


	sprintf(cmdbuf, "sort < %s > %s", datafile, sortedfile);

	fp = fopen(sortedfile, "r");
	/* read sorted data from fp... */

See also question 12.28b.

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North