如何通过Qt修改记事本编码,强制其以正确编码读取文件?
Hey there! Let's fix that annoying encoding mismatch when launching Notepad via Qt. Here are a few practical, actionable methods to make Notepad use the right encoding every time:
1. Use Notepad's Built-in /Encoding Parameter (Windows 10 1809+)
Starting with Windows 10 October 2018 Update, Notepad supports an /Encoding command-line argument that lets you explicitly specify the encoding. You can use either the encoding name (like UTF-8) or its corresponding Windows code page number (more reliable for older regional encodings).
In your Qt code, launch Notepad with this parameter like so:
QString targetFilePath = "C:/path/to/your/file.txt"; // Replace 65001 with your correct encoding's code page: // - 65001 = UTF-8 // - 936 = GBK (Simplified Chinese) // - 1252 = Windows-1252 (ANSI for Western languages) // - 1200 = UTF-16LE QProcess::startDetached("notepad.exe", QStringList() << "/Encoding" << "65001" << targetFilePath);
This directly tells Notepad which encoding to use, no guesswork involved.
2. Add a BOM to the File (If Modifying the File Is Acceptable)
If your target system doesn't support the /Encoding parameter (older Windows versions), you can add a Byte Order Mark (BOM) to the file. Notepad automatically detects BOMs and uses the matching encoding.
For example, to add a UTF-8 BOM:
QFile file(targetFilePath); if (file.open(QIODevice::ReadWrite)) { QByteArray originalContent = file.readAll(); file.seek(0); // Write UTF-8 BOM (EF BB BF) file.write("\xEF\xBB\xBF"); file.write(originalContent); file.close(); } // Now launch Notepad normally QProcess::startDetached("notepad.exe", QStringList() << targetFilePath);
⚠️ Note: This modifies the original file. Only use this if you don't mind altering the file's content.
3. Pipe File Content via Command Prompt (View-Only Scenario)
If you can't modify the file and can't use the /Encoding parameter, you can pipe the file content through Command Prompt with the correct encoding set. This opens the content in Notepad for viewing, but you won't be able to save changes back to the original file directly.
Here's the Qt code for this approach:
QString targetFilePath = "C:/path/to/your/file.txt"; // Replace 65001 with your desired code page QString cmd = QString("chcp %1 && type %2 | notepad.exe") .arg("65001") .arg(QDir::toNativeSeparators(targetFilePath)); QProcess::startDetached("cmd.exe", QStringList() << "/c" << cmd);
This switches the command prompt's code page first, then sends the file content to Notepad, ensuring it's displayed with the correct encoding.
内容的提问来源于stack exchange,提问作者user12991669

