小编The*_*rty的帖子

为什么stdin和stdout看似可以互换?

我知道stdin和stdout(至少在UNIX用语中)是流缓冲区,并且stdout用于从程序输出到控制台(或者然后由shell管道等),并且stdin用于标准输入一个程序..

那么为什么至少在macOS上它们可以互换使用(stdout作为stdin,反之亦然?

例子:

  1. 如果你运行cat /dev/stdin然后输入内容,它会回复它.像cat /dev/stdout同样的事情一样运行命令.

  2. 类似地,echo "Hey There" > /dev/stdoutecho "Hey There" > /dev/stdin两个输出"嘿"回终端.

  3. 它也适用于C++:

例:

#include <iostream>
#include <string>
#include <fstream>

int main(int argc, const char * argv[]) {
    std::string echoString;
    std::fstream stdoutFile;
    stdoutFile.open("/dev/stdout");
    stdoutFile << "Hey look! I'm using stdout properly!\nNow You trying using it wrongly: " << std::endl;
    stdoutFile >> echoString;
    stdoutFile << "You Typed: " << echoString << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

出现提示时,键入单个单词,然后按EOF(Ctrl + D)按预期工作.

c++ unix macos shell stdout

7
推荐指数
1
解决办法
178
查看次数

标签 统计

c++ ×1

macos ×1

shell ×1

stdout ×1

unix ×1