Reset the console color to its default in c++ for linux console

758 views Asked by At

I am writing a C++ program that is changing the color of the console output. I already managed to colorize output on Windows and Linux systems. Also, I am able to restore the default color on a Windows system.

#include <iostream>
#if defined(_WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64)
#include <windows.h>
#endif

#if defined (__linux__)|| (__OSX__)
  int main() 
    {

      std::cout << "we are on Linux" << std::endl;
      std::cout << "\033[31mred text\n"<< std::endl;
      std::cout << "I\033[31am \033[33mrainbow \033[34mText\033[0m\n"; 
      //rainbow text with color set to white at the end   
    
      return 0;

    }
#elif defined(_WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64)

  using namespace std;

  int main() 
    {
      //create handle
      HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);

      //get console colour information
      CONSOLE_SCREEN_BUFFER_INFO csbi;
      GetConsoleScreenBufferInfo( h, &csbi );
      
      cout <<"\nWe're on Windows!" << endl;

      cout << "\n\n";
      //default color
      cout << "ColorText" << endl;

      //yellow
      SetConsoleTextAttribute(h,6);
      cout << "ColorText" << endl;

      //blue
      SetConsoleTextAttribute(h,3);
      cout << "ColorText" << endl;

      //white
      SetConsoleTextAttribute(h,7);
      cout << "ColorText" << endl;
  
      //red    
      SetConsoleTextAttribute(h,12);
      cout << "ColorText" << endl;

      //set console back to default
      SetConsoleTextAttribute( h, csbi.wAttributes );
    
      return 0;

    
    }
#else
  int main()
    {
        std::cout << "Unsupported system" << std::endl;
        return 0;
    }
#endif

But I haven't found a way, to store the basic color for Linux consoles in c++. I first thought about, setting it back to white, but there are cases, where the default console color is green or blue. In those cases, I would change the “user experience” outside my program.

0

There are 0 answers