diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 3d4b08ea..0f4c4729 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -42,3 +42,4 @@ cppterminal_example(SOURCE slow_events) cppterminal_example(SOURCE utf8) cppterminal_example(SOURCE attach_console WIN32) cppterminal_example(SOURCE attach_console_minimal WIN32) +cppterminal_example(SOURCE pipe_cin) diff --git a/examples/pipe_cin.cpp b/examples/pipe_cin.cpp new file mode 100644 index 00000000..beb84ebb --- /dev/null +++ b/examples/pipe_cin.cpp @@ -0,0 +1,80 @@ +/* +* cpp-terminal +* C++ library for writing multi-platform terminal applications. +* +* SPDX-FileCopyrightText: 2019-2023 cpp-terminal +* +* SPDX-License-Identifier: MIT +*/ + +#include "cpp-terminal/color.hpp" +#include "cpp-terminal/terminal.hpp" + +#include +#include +#include +#include + +namespace +{ + +bool isStdinEmpty() +{ + struct timeval tv + { + 0, 0 + }; + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(STDIN_FILENO, &rfds); + return select(STDIN_FILENO + 1, &rfds, nullptr, nullptr, &tv) == 0; +} + +std::string ReadStdin() +{ + if(isStdinEmpty()) { return "stdin is empty"; } + std::string stdin_result; + char c; + while((c = static_cast(std::fgetc(stdin))) != EOF) + { + if(c == '\n') break; + stdin_result += c; + } + return stdin_result; +} + +bool isCinPipe() { return isatty(fileno(stdin)) == 0; } + +std::string ReadCin() +{ + if(!isCinPipe()) { return "std::cin isn't an unamed pipe"; } + std::string cin_result; + char c; + while((c = static_cast(std::cin.get())) != '\n') { cin_result += c; } + return cin_result; +} + +std::ostream& PrintOutColor(std::ostream& ostr, std::string const& str, Term::Color::Name color) +{ + ostr << "\"" << Term::color_fg(color) << str << Term::color_fg(Term::Color::Name::Default) << "\"" << std::endl; + return ostr; +} + +} // namespace + +int main() +{ + std::string cinBuff{}; + + std::cout << "Checking if std::cin is empty" << std::endl; + cinBuff = ReadCin(); + std::cout << "std::cin => "; + PrintOutColor(std::cout, cinBuff, Term::Color::Name::Red); + + std::cout << "Checking if stdin is empty" << std::endl; + cinBuff = ReadStdin(); + std::cout << "stdin => "; + PrintOutColor(std::cout, cinBuff, Term::Color::Name::Red); + + return 0; +}