之前的文章介紹如何讀取 UTF-8 檔案。
Qt 如何從檔案讀取 UTF-8 的中文
這次介紹如何將 UTF-8 檔案轉存為 UTF-16。
使用 QFile 開啟檔案,
使用 QTextStream 處理編碼,
=== 完整範例
 QFile fileIn("input.txt");
 if (!fileIn.open(QIODevice::ReadOnly | QIODevice::Text))
 {
  qDebug() << "fileIn opne fail.";
  return;
 }
 QFile fileOut("output.txt");
 if (!fileOut.open(QIODevice::WriteOnly | QIODevice::Text))
 {
  qDebug() << "fileOut opne fail.";
  return;
 }
 QTextStream in(&fileIn);
 in.setCodec("UTF-8");
 QTextStream out(&fileOut);
 out.setCodec("UTF-16");
 while (!in.atEnd()) {
  QString line = in.readLine();
  out << changeText(line);
 }
 fileIn.close();
 fileOut.close();
 qDebug() << "done";
=== 資料來源
Qt Documentation - QTextStream Class
http://doc.qt.io/qt-5/qtextstream.html
 
沒有留言:
張貼留言