Sunday, August 12, 2012

Programming with C++ on MAC - Sending output to a terminal window.

     For a long time I have wanted to take my console output from C++ programs out of the Xcode debug window and into a terminal window. However, there is no simple way to do this with the standard library (std::). Today I asked myself the question if every piece of hardware on a unix/nix machine is represented by a file can I just use standard file streams to send data to the terminal window? Surely this is what programs already do send data to the debug logs and the terminal window. However, what if I need more than one terminal window open to display more data?? Running TOP is one example, often when using programs like TOP the terminal window is loaded with lines of running programs and services, it would be nice to have a second window with the overflow displayed in that window. Although it is not my intention to write such an extension to TOP it does give me a solution for an upcoming project where I need OpenGL and text data send to a terminal. Before running this bit of code make sure a terminal window is open.

#include  
#include
#include
#include
int main(int argc, char * const argv[]) 


     //output to the mac terminal 
     std::ofstream term("/dev/ttys001", std::ios_base::out); 

     term << "\n\nTerminal Output - Hello World!!!\n\n"; 

     std::cout << "\n\nstdout - Hello I am in the debug window!!!\n\n"; 

     return 0; 

}

That is all it takes. Such a simple solution to a simple problem. So when people tell you that you "can't have your cake and eat it to" now you can tell them that you can.