现在的位置: 首页 > 综合 > 正文

基于Qt平台的Mac可读系统版本的获取

2013年10月09日 ⁄ 综合 ⁄ 共 2082字 ⁄ 字号 评论关闭

基于Qt开源的Tianchi项目,需要加入关于获取mac os x的版本,开源项目详见天池开源项目

首先我们看下命令行获取Mac OS X的版本信息,如下:

Mac系统打开命令行终端的方法:

     应用程序 --> 实用工具 --> 终端

Mac系统终端查看操作系统版本号的方法:

     #more /System/Library/CoreServices/SystemVersion.plist

    输出详见:

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/   
PropertyList-1.0.dtd">  
<plist version="1.0">  
<dict>  
        <key>ProductBuildVersion</key>  
        <string>9F33</string>  
        <key>ProductCopyright</key>  
        <string>1983-2008 Apple Inc.</string>  
        <key>ProductName</key>  
        <string>Mac OS X</string>  
        <key>ProductUserVisibleVersion</key>  
        <string>10.6.7</string>  
        <key>ProductVersion</key>  
        <string>10.6.7</string>  
</dict>  
</plist>

其中的10.6.7就是Mac OS X的版本号。

话说,命令行拿到systemversion的plist的内容,如何解析呢?基于Qt下如何解析?

且看Qt下面也有解析xml文件的类,试着像解析xml文件一样解析plist

下面代码把所有的节点都解析到QTreeWidget里面

     QTreeWidget tree;
     QString     fileCfg;
     fileCfg = "/System/Libary/CoreServices/SystemVersion.plist";
     DomParser domParserCfg(&tree);
     domParserCfg.readFile(fileCfg);  //readFile 是DomParser的解析接口函数
     QString strVer = domParserCfg.pcVersion;   //pcVersion为DomParser 的一个public成员变量
//下面是DomParser 解析的部分代码

bool DomParser::readFile(QString fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly|QFile::Text))
    {
        return false;
    }
 const QByteArray & buffe = file.readAll();
    QString errorstr;
    int errorLine;
    int errorCol;

    QDomDocument doc;
    if(!doc.setContent(buffe, false, &errorstr, &errorLine, &errorCol))
    {
        return false;
    }

    QDomElement root = doc.documentElement();

     if (root.tagName() == "plist")
    {
        ParserListElement(root);
        return true;
    }
   else
   {
       return false;
    }

 return false;
    
}
 void DomParser::ParserListElement(const QDomElement &element)
{
    QDomNode child = element.firstChild();
    while(!child.isNull())
    {
        if(child.toElement().tagName() == "dict")
        {
            ParserDictElement(child.toElement(),treeWidget->invisibleRootItem());
        }
        child = child.nextSibling();
    }
}

void DomParser::ParserDictElement(const QDomElement &element, QTreeWidgetItem *parent)
{
    QTreeWidgetItem *item = new QTreeWidgetItem(parent);

    QDomNode child = element.firstChild();
    while(!child.isNull())
    {
        if(child.toElement().tagName() == "key")
        {
            if(child.toElement().text() == "CFBundleVersion")
            {
                child = child.nextSibling();
                pcVersion = child.toElement().text();
                return;
            }
        }
        child = child.nextSibling();
    }
}

【上篇】
【下篇】

抱歉!评论已关闭.