這裡寫了一個例子,
Info.uni是一個Unicode(UTF-16)的檔案,執行這一個檔案會,
會多出一個CopyInfo.uni(UTF-16)的檔案與Info.txt(ANSI)
另外,因為,在Qt中,讀取UTF-16與ANSI的方式是一樣的,所以,
當你把Info.uni的內容改成ANSI的話,同樣程式可以work,
並且一樣會產生出CopyInfo.uni(UTF-16)的檔案與Info.txt(ANSI)
範例程式碼如下:
main.cpp
#include <QFile>
#include <QDebug>
#include <QTextStream>
#include <QStringList>
int main(int argc, char *argv[])
{
QFile UnicodeFile("Info.uni");
QFile CopyUnicodeFile("CopyInfo.uni");
QFile ANSIFile ("Info.txt");
QStringList ContainStringList;
//
// Try to open Unicode file
//
if (!UnicodeFile.open(QIODevice::ReadOnly)) {
qDebug () << "Open UnicodeFile error!!";
return -1;
}
//
// Create a QTextStream for UnicodeFile
//
QTextStream UnicodeOut (&UnicodeFile);
//
// Insert all the contain into ContainStringList
//
while (!UnicodeOut.atEnd()) {
//qDebug() << UnicodeOut.readLine();
ContainStringList << UnicodeOut.readLine();
}
UnicodeFile.close();
//
// Try to create a unicode file
//
if (!CopyUnicodeFile.open(QIODevice::WriteOnly)) {
qDebug() << "Open CopyUnicodeFile error!!";
return -1;
}
QDataStream CopyUnicodeData(&CopyUnicodeFile);
//
// Create Unicode header (FFFE) for CopyInfo.uni
//
CopyUnicodeData << (quint8) 0xFF << (quint8) 0xFE;
CopyUnicodeFile.close();
if (!CopyUnicodeFile.open(QIODevice::Append | QIODevice::Text)) {
qDebug() << "Open CopyUnicodeFile error!!";
return -1;
}
QTextStream CopyUnicodeOut (&CopyUnicodeFile);
CopyUnicodeOut.setCodec("UTF-16");
//
// Insert all the contain from ContainStringList into CopyInfo.uni (Unicode decode)
//
for (int i = 0; i < ContainStringList.size();) {
CopyUnicodeOut << ContainStringList.at(i++);
if (i < ContainStringList.size()) {
CopyUnicodeOut << endl;
}
}
CopyUnicodeFile.close();
//
// Try to create a ANSI file
//
if (!ANSIFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Open ANSIFile error!!!";
return -1;
}
//
// Try to create a ANSI file
//
QTextStream ANSIOut (&ANSIFile);
//
// Insert all the contain from ContainStringList into Info.txt (ANSI decode)
//
for (int i = 0; i < ContainStringList.size();) {
ANSIOut << ContainStringList.at(i++);
if (i < ContainStringList.size()) {
ANSIOut << endl;
}
}
ANSIFile.close();
return 0;
}
參考資料:
QString Class Reference
建立一個Unicode檔案的簡單程式
沒有留言:
張貼留言