views:

87

answers:

2

I'm designing a MIPS simulator in c++ and my simplified OS must be able to run stat() occasionally (when a program being executed on my simulator requires an input or an output or something.)

The problem is, I need to be able to assert STDIN, STDOUT, and STDERR as parameters to stat "stat("stdin",buff)" where buff is the pointer to the insertion point, for the struct data returned, in memory. In reality I'll be using fstat() which uses file descriptors to point to the file to be stat-ed. My file descriptor table in my simple OS reserves 0, 1, and 2 for stdin, stdout, and stderr. I'm a bit confused about what STDIN, etc are. They're streams, I realize that, they're defined in stdio.h, but how in the world do I get a stat struct with all of the relevant information about the file for each of these streams?

+1  A: 

On a POSIX system, you can use fileno() to convert from a FILE* (e.g. stdin, stdout, stderr) to an integer file descriptor. That file descriptor can be sent to fstat(), as James said.

Drew Hall
As far as I understood 0, 1, and 2 were reserved file descriptors for stdin, stdout, and stderr. So my file descriptor table can supply stat() with the filenames of the files. The thing is, my file descriptor table in c++ is a vector in which I push the filename of an opened file into the vector, and the first three elements of the vector at startup are "STDIN", "STDOUT", and "STDERR". But I don't know how exactly to run stat() on STDIN (for example). Does stdin make a temporary file that I can run stat() on?
Dan Snyder
A: 

Here is a very well known example of how to determine if the standard terminal output is redirected to a file to illustrate the usage of POSIX's fileno function

if (!isatty(fileno(stdout))){
    fprintf(stdout, "argv, argc, someone is redirecting me elsewhere...\n");
    return 1;
}

If using the above code in a program and that said program was executed like this

foobar_program > foobar_program.output

'foobar_program.output' will contain

argv, argc, someone is redirecting me elsewhere...\n

A file stream pointer is nothing more than a structure of a pointer type to FILE, i.e. FILE *, fileno takes that structure and converts it to its relevant file descriptor, accordingly to the manual page for fileno here

The function fileno() examines the argument stream and returns 
its integer descriptor.

and also here on the posix manual pages, and I'll quote fileno - map a stream pointer to a file descriptor....

tommieb75