msk@afinitc.UUCP (11/13/84)
Please pardon my ignorance, but I would like to know how to set up a C program to do output to a particular file descriptor so that I may redirect the output to a given file. (If no redirection is specified, then of course I can output to a default file) I mean, how can I program the following: program > output 2> error 3> my_file ---------- Please mail me responses and I will report the various options for code fragments to the net. THANKS! -- -- From the terminal of Morris Kahn (...ihnp4!wucs!afinitc!msk) -- Affinitec, Corp., 2252 Welsch Ind. Ct., St. Louis, MO 63146 (314)569-3450
davidt@ttidca.UUCP (David Terlinden) (11/21/84)
Use Bourne shell, not C shell. Just something like prog 3>/dev/tty to shell and write(3, "hello!!!", 8); in C program works fine.
jsdy@SEISMO.ARPA (01/04/85)
> how can I program the following: > program > output 2> error 3> my_file This is not a good way to do what it seems you want to do. If you really want to, though, try the following: -------------------- #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #define FDES 3 #define ROPEN 0 #define WOPEN 1 #define PRVMOD 0600 char file[] = ".cshrc"; main() { register int i, j; struct stat sb; if (fstat(FDES, &sb) < 0) { j = i = open(file, WOPEN); if (i < 0) j = i = creat(file, PRVMOD); if (i >= 0 && i != FDES) { j = dup2(i, FDES); close(i); } printf("Opened <%s> on %d (%d)\n", file, j, i); } else printf("File type is 0%o\n", sb.st_mode); /* Put the UNIX file descriptor into a stdio structure. */ /* Rest of code */; } -------------------- A better way to program this would be: -------------------- [preamble] main(argc, argv, envp) int argc; char **argv; char **envp; { register char *fp = file; register FILE *fstream; if (--argc > 0) fp = *++argv; fstream = fopen(fp, WRITE); /* Rest of code */; } -------------------- This is called as 'program ...' or 'program ... my_file', depending on whether you want it to use the default file or your special file. Note that you don't have to depend on a non-stdio construct like dup2, or UNIX's reliability in opening file descriptors serially, or anything like that. Joe Yao (UUCP!seismo!hadron!jsdy / hadron!jsdy@seismo.ARPA)