編集:この問題の解決策は、以下のコメントで Ulrich Eckhardt によって提供されました。また、この問題には、重複の可能性で説明されているものとはまったく異なる原因と解決策がありました。詳細については、Ulrich Eckhardt のコメントを参照してください。
ここの専門家の助けを借りて、指定されたコード ページで Windows クリップボードの内容をテキスト ファイルに書き込むプログラムを作成することができました。テキスト ファイルの改行が 0d 0a ではなく 0d 0d 0a の 3 バイトであることを除いて、完全に機能するようになりました。これにより、テキストをワープロにインポートすると問題 (追加の行) が発生します。
テキスト ストリームで 0d 0d 0a を 0d 0a に置き換える簡単な方法はありますか、それともコードで別の方法で行うべきことはありますか? 私は他の場所でこのようなものを見つけていません。コードは次のとおりです。
#include <stdafx.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <codecvt> // for wstring_convert
#include <locale> // for codecvt_byname
using namespace std;
void BailOut(char *msg)
{
fprintf(stderr, "Exiting: %s\n", msg);
exit(1);
}
string ExePath()
{
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
string::size_type pos = string(buffer).find_last_of("\\/");
return string(buffer).substr(0, pos);
}
// get output code page from command-line argument; use 1252 by default
int main(int argc, char *argv[])
{
string codepage = ".1252";
if (argc > 1) {
string cpnum = argv[1];
codepage = "." + cpnum;
}
// HANDLE clip;
string clip_text = "";
// exit if clipboard not available
if (!OpenClipboard(NULL))
{ BailOut("Can't open clipboard"); }
if (IsClipboardFormatAvailable(CF_TEXT)) {
HGLOBAL hglb = GetClipboardData(CF_TEXT);
if (hglb != NULL) {
LPSTR lptstr = (LPSTR)GlobalLock(hglb);
if (lptstr != NULL) {
// read the contents of lptstr which just a pointer to the string:
clip_text = (char *)hglb;
// release the lock after you're done:
GlobalUnlock(hglb);
}
}
}
CloseClipboard();
// create conversion routines
typedef std::codecvt_byname<wchar_t, char, std::mbstate_t> codecvt;
std::wstring_convert<codecvt> cp1252(new codecvt(".1252"));
std::wstring_convert<codecvt> outpage(new codecvt(codepage));
std::string OutFile = ExePath() + "\\#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 << "Error opening file " << OutFile << " for writing.\n";
return 1;
}
// convert to DOS/Win codepage number in "outpage"
OutStream << outpage.to_bytes(cp1252.from_bytes(clip_text)).c_str();
//OutStream << endl;
OutStream.close(); // close output stream
return 0;
}