Are stdin, stdout, and stderr Files?

2019-05-24 08:11发布

问题:

Someone told me that whenever a C++ program is run three files STDIN, STDOUT and STDERR are opened and he gave this link in his support..

http://tldp.org/LDP/abs/html/io-redirection.html

But I am confused weather these streams are actually Files?

Can anyone clarify?

回答1:

On POSIX systems, streams are special file descriptors. Windows has its own err.. thing, but they are file descriptors there as well. Examples of special files on Windows are the standard streams stdout, stdin and stderr, as well as serial ports like COMn, which can be opened with OpenFile(). On Linux, special files are found under /proc and /dev. /proc/cpuinfo will read back information about your CPU. /dev/sdX are handles to your physical disks, etc.

So what's a special file? It's a file handle, but the contents isn't stored on disk. The file handle is just an interface to the kernel. On POSIX systems you use open(), close(), read(), write(), and ioctl() to talk to the kernel via the file descriptor. Even a file descriptor to the whole memory map is available, under /dev/mem. You open this and pass to mmap() if you want to map a memory region for example.

Unfortunately Microsoft Windows does not handle file descriptors at this level. I wish Windows was more POSIX-like.



回答2:

If you type man stdio on your terminal the synopsis looks like this

#include <stdio.h>

 FILE *stdin;
 FILE *stdout;
 FILE *stderr;

So they really are files.

If you are asking if these files actually exists somewhere, have a look at /dev/stdin, /dev/stdout and /dev/stderr .



回答3:

They are of type FILE*. They can be used like files with IO functions. But they aren't 'real' files - they are the standard IO streams. When you do something like this in your shell (example for linux):

cat something.txt | myprog

...then myprog can read the contents of something.txt (output of the cat program) by reading from STDIN.



标签: c++ stream