Datei-Encoding (OEM->UTF8)



  • Hallo,

    ich habe folgendes Problem: Ich möchte eine Quelldatei mit OEM-Zeichensatz (Codepage 437) einlesen und eine Kopie in UTF-8 Kodierung wieder abspeichern. Die Quelldatei verwendet u.a. Sonderzeichen um Kästchen darzustellen, die ich natürlich auch in der Zieldatei so sehen möchte.

    Mit C# bekomme ich das ganz einfach hin:

    StreamReader sr = new StreamReader(@"c:\quelle.txt", Encoding.GetEncoding(437));
    StreamWriter sw = new StreamWriter(@"c:\ziel.txt", false, Encoding.UTF8);
    
    while(true)
    {
      string line = sr.ReadLine();
      if (line == null)
        break;
      sw.WriteLine(line);
    }
    sw.Flush();
    sw.Close();
    

    Hat jemand eine Idee, wie ich das mit C++/MFC realisieren kann?
    Habe mir schon _wfopen_s angeschaut, aber da gibt es keinen Parameter, mit dem sich das Encoding auf Codepage 437 setzen ließe.

    Gruß, Thomas



  • Zuerst die CP 437 mittels MutliByteToWideChar nach UTF16 konvertieren und dann zurück nach UTF8 mit WideCharToMultiByte.

    Was anderes macht .NET auch nicht 😉



  • Hallo Jochen,

    danke für den Tipp. Die Konvertierung läuft auf den ersten Blick jetzt so wie ich mir das wünsche.

    Anbei mein Quellcode. Falls jemand noch eine böse Falle entdeckt bin ich für Verbesserungsvorschläge dankbar! 🙂

    #define BUFFSIZE1 512
    #define BUFFSIZE2 2048
    
    // define some buffers
    char	cBuf[BUFFSIZE1];
    WCHAR	wcBufUTF16[BUFFSIZE2];
    char	cBufUTF8[BUFFSIZE2];
    
    // get the buf pointers
    char*	pcBuf		= &cBuf[0];
    WCHAR*	pwcBufUTF16 = &wcBufUTF16[0];
    char*	pcBufUTF8	= &cBufUTF8[0];
    
    // open input file, create output file
    CStdioFile fr, fw;
    if (!fr.Open(_T("c:\\quelle.txt"), CFile::modeRead))
    	return; // error
    if (!fw.Open(_T("c:\\ziel.txt"), CFile::modeWrite | CFile::modeCreate))
    	return; // error
    
    // init buffers
    ZeroMemory(pcBuf,		BUFFSIZE1);
    ZeroMemory(pwcBufUTF16, BUFFSIZE2);	
    ZeroMemory(pcBufUTF8,	BUFFSIZE2);	
    
    // read input file, write output file
    while (0 < fr.Read(pcBuf, BUFFSIZE1))
    {
      // convert from Codepage 437 to UTF-16
    	int nChars = MultiByteToWideChar(437, 0, pcBuf, BUFFSIZE1, pwcBufUTF16, 0);
    	MultiByteToWideChar(437, 0, pcBuf, BUFFSIZE1, pwcBufUTF16, nChars);
    
    	// convert from UTF-16 to UTF-8
    	nChars = WideCharToMultiByte(CP_UTF8, 0, pwcBufUTF16, nChars, pcBufUTF8, 0, NULL, NULL);
    	WideCharToMultiByte(CP_UTF8, 0, pwcBufUTF16, nChars, pcBufUTF8, nChars, NULL, NULL);
    
      // write UTF-8 data to output file 
    	fw.Write(pcBufUTF8, nChars);
    
    	// re-init buffers
    	ZeroMemory(pcBuf,		BUFFSIZE1);
    	ZeroMemory(pwcBufUTF16, BUFFSIZE2);	
    	ZeroMemory(pcBufUTF8,	BUFFSIZE2);
    }
    // flush and close output file
    fw.Flush();
    fw.Close();
    

    Gruß, Thomas


Anmelden zum Antworten