C Interview Questions and Answers

 

How can I call system when parameters (filenames, etc.) of the executed command arent known until run time?

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;



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... */





fclose(fp);





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



system(cmdbuf);





fp = fopen(sortedfile, "r");



/* ...now read sorted data from fp... */

Posted by:Richards