Redirect output file descriptor 3 (not just 1 and 2)

jsdy at SEISMO.ARPA jsdy at SEISMO.ARPA
Fri Jan 4 15:11:55 AEST 1985


>         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 at seismo.ARPA)



More information about the Comp.lang.c mailing list