Accessing clipboard (copy paste) from C++ program on Mac OS X

Alec Jacobson

January 02, 2012

weblog/

I've been using pbcopy and pbpaste to control the clipboard via the command on mac for a while now. It's not to hard to utilized these in a c++ program, integrating my little apps with the clipboard without having to go through Cocoa or objective c or any libraries. Here's a little demo:
#include <string>
#include <iostream>
#include <sstream>
#include <stdio.h>

// http://stackoverflow.com/questions/478898
std::string exec(const char* cmd)
{
  FILE* pipe = popen(cmd, "r");
  if (!pipe) return "ERROR";
  char buffer[128];
  std::string result = "";
  while(!feof(pipe))
  {
    if(fgets(buffer, 128, pipe) != NULL)
    {
      result += buffer;
    }
  }
  pclose(pipe);
  return result;
}

std::string paste()
{
  return exec("pbpaste");
}

std::string copy(const char * new_clipboard)
{
  std::stringstream cmd;
  cmd << "echo \"" << new_clipboard << "\" | pbcopy";
  return exec(cmd.str().c_str());
}

int main(int argc, char * argv[])
{
  using namespace std;
  cout<<"old clipboard: "<<paste()<<endl;
  copy("Bomb!");
  cout<<"new clipboard: "<<paste()<<endl;
  return 0;
}