lundi 29 juin 2015

C++ (VC) Text output breaks lines with 0d 0d 0a instead of 0d 0a - how to fix?


With the help of the experts here, I managed to put together a program that writes the contents of the Windows clipboard to a text file in a specified code page. It now seems to work perfectly, except that the line breaks in the text file are three bytes - 0d 0d 0a - instead of 0d 0a - and this causes problems (additional lines) when I import the text into a word processor.

Is there an easy way to replace 0d 0d 0a with 0d 0a in the text stream, or is there something I should be doing differently in my code? I haven't found anything like this elsewhere. Here is the code:

#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;
}


Aucun commentaire:

Enregistrer un commentaire