簡體   English   中英

如何檢查std :: cin是否與終端或管道關聯

[英]How to check if std::cin is associated with a terminal or a pipe

如何檢查std :: cin緩沖區是否與終端或管道相關聯?

命令行顯示std :: cin與文件關聯:

Application.exe < C:\output.txt > C:\result.txt

顯示與終端關聯的std :: cin的命令行:

Application.exe

我試圖為此目的分析in_avail()。 但這並沒有幫助。

std::cin.rdbuf()->in_avail()

std::istream::peek引用

如果good() == true ,則返回rdbuf()->sgetc()獲得的下一個字符,否則,返回Traits::eof()

這意味着它將返回下一個可用字符或eof標志。

並且,如果需要,將導致調用底層緩沖區underflow函數,如果有任何要從操作系統讀取的內容,該函數將填充緩沖區。

這將適用於文件輸入(和用戶輸入):

#include <iostream>
#include <sstream>

int main(int argc, const char * argv[])
{
    typedef std::istream::traits_type Traits;
    std::stringstream buffer;
    Traits::int_type ch;
    while((ch = std::cin.get()) != Traits::eof()) {
        buffer << Traits::to_char_type(ch);
    }
    std::cout << buffer.str();
}

需要用戶在(linux)終端中輸入<ctrl-d>才能停止讀取。

沒有其他方法(基本上)可以檢測cin是否具有(將獲得)可用字符(盡管某些協議可以處理用戶輸入)。

我找到了問題的答案。

首先,我必須以正確的方式提問。
我想問的問題:如何確定std :: cin是否與終端或管道關聯。


在Windows上:

_isatty( _fileno(stdin) );

在POSIX上:

isatty( fileno(stdin) );


在Windows上:

如果stdin與char設備關聯,則_isatty調用retursn非零值。

在POSIX上:

如果stdin指向終端,則isatty調用返回1。


Linux的isatty man: http : //man7.org/linux/man-pages/man3/isatty.3.html
_isatty在MSDN上的人: http//msdn.microsoft.com/zh-cn/library/f4s0ddew.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM