title: C++ (VC): How to detect whether Windows clipboard contains CF_TEXT data?
body: <p>I'm a complete beginner at C++, but I've managed to modify other people's code and finally put together a program that writes the Windows clipboard to a text file, with the text encoded in the codepage specified as a command line parameter for the program (for example, MyProg.exe 437) will write the text in codepage 437. If no codepage is specified, the program writes a text file in the standard Windows codepage 1252.</p>
  
  <p>The trouble is that the program crashes if the clipboard contains (for example) a shortcut or file, not text. Can someone tell me how I can exit gracefully if there is no <code>CF_TEXT</code> data in the clipboard? (Or have I completely misunderstood the problem?) </p>
  
  <p>I've searched for an answer with no success. Here is my VC2010 code (which I don't entirely understand, but it seems to work, when the clipboard contains <code>CF_TEXT</code>; it doesn't work with <code>CF_UNICODETEXT</code>, by the way - the output is simply a few bytes.):</p>
  
  <pre><code>#include &lt;stdafx.h&gt;
  #include &lt;windows.h&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;codecvt&gt; // for wstring_convert
  #include &lt;locale&gt;  // for codecvt_byname
  
  using namespace std;
  
  void BailOut(char *msg)
  {
  fprintf(stderr, "Exiting: %s\n", msg);
  exit(1);
  }
  
  int main(int argc, char* argv[])
  {
  std::string codepage = ".1252";
  if (argc &gt; 1) {
      std::string cpnum = argv[1];
      codepage = "."+cpnum;   
  }
  
  HANDLE clip;
  string clip_text = "";
  // exit if clipboard not available
  if (!OpenClipboard(NULL))
          BailOut("Can't open clipboard"); 
  
  clip = GetClipboardData(CF_TEXT);
  clip_text = (char*)clip;
  CloseClipboard();
  
  // create conversion routines
  typedef std::codecvt_byname&lt;wchar_t,char,std::mbstate_t&gt; codecvt;
  std::wstring_convert&lt;codecvt&gt; cp1252(new codecvt(".1252"));
  std::wstring_convert&lt;codecvt&gt; outpage(new codecvt(codepage));
  
  std::string OutFile = "#clip.txt"; // output file name
  ofstream OutStream;  // open an output stream
  OutStream.open(OutFile, ios::out | ios::trunc);
  
  // make sure file is successfully opened
  if(!OutStream)
  {
      cout &lt;&lt; "Error opening file " &lt;&lt; OutFile &lt;&lt; " for writing.\n";
      return 1;
  }
  // convert to DOS/Win codepage number in "outpage"
  OutStream &lt;&lt; outpage.to_bytes(cp1252.from_bytes(clip_text)).c_str();
  OutStream &lt;&lt; endl;
  OutStream.close(); // close output stream
  return 0;
  } 
  </code></pre>
  
  <p>I'll be grateful for any suggestions on how to fix this last problem.</p>