遇到的问题
查看前辈的Qt代码,发现好多没用的代码注释掉了,但是没删,而且这种代码非常多,所以想将这些注释删除掉。整体设计思路如下:
1、注释就是两种情况: ‘//’ 和’/* /’,其中/之中也可能会包含//
2、定义三种模式:自由查找、找到了/、找到了/
直接上代码
ui->progressBar->setMaximum(ui->listWidget->count());
ui->progressBar->setValue(0);
ui->progressBar->setVisible(true);
for(int i=0; i<ui->listWidget->count(); i++)
{
ui->progressBar->setValue(i);
QString fileName = ui->listWidget->item(i)->text();
ui->textEdit->append(tr("开始处理:") + fileName);
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly))
{
ui->textEdit->append(tr("打开文件失败:%1").arg(fileName));
continue;
}
QTextStream in(&file);
in.setCodec("utf-8");
QString strLine;
m_iRow = 0;
m_type = TYPE_NONE;
int pos = -1;
QStringList strList;
while(in.readLineInto(&strLine))
{
m_iRow++;
//查找模式
if(m_type == TYPE_NONE)
{
int pos1 = strLine.indexOf("//");
int pos2 = strLine.indexOf("/*");
int pos3 = strLine.indexOf("*/");
//找到'//'
if(pos1 > -1)
{
//同时也找到了'/*',并且'//'在前面,那么//后面的全是注释,同时模式为查找模式
if(pos1 < pos2)
{
pos = pos1;
m_type = TYPE_NONE;
}
else
{
//同时也找到了'/*',并且'//'在后面,那么模式为查找'*/',中间的全部都是注释
if(pos2 > -1)
{
pos = pos2;
m_type = TYPE_BEGIN;
}
//如果没有'/*',那这一行为注释行
else
{
pos = pos1;
m_type = TYPE_NONE;
}
}
}
else
{
//没有找到'//',但是找到了'/*'
if(pos2 > -1)
{
pos = pos2;
m_type = TYPE_BEGIN;
}
//什么也没找到,继续寻找
else
{
}
}
//如果同时找到了'/*'和'*/',将中间的注释去掉
if(pos2 > -1 && pos3 > -1)
{
QString strMsg = strLine.mid(pos2, pos3-pos2+2);
AppendLog(strMsg);
strLine = strLine.remove(strMsg);
pos = -1;
m_type = TYPE_NONE;
}
}
else
{
//查找'*/'模式,如果找到,'*/'前面的全部移除,没有找到那么从0开始整行移除
int pos3 = strLine.indexOf("*/");
if(pos3 > -1)
{
m_type = TYPE_END;
pos = pos3;
}
else
{
pos = 0;
}
}
//POS来表明是否为需要处理的注释
if(pos > -1)
{
//如果是'//','/*'都是移除后面的,'*/'移除前面的
if(m_type != TYPE_END)
{
QString strMsg = strLine.mid(pos);
AppendLog(strMsg);
strLine = strLine.left(pos);
}
else
{
QString strMsg = strLine.left(pos+2);
AppendLog(strMsg);
strLine = strLine.mid(pos+2);
m_type = TYPE_NONE;
}
//除非是开始模式,否则全部置-1,处理已经完毕
if(m_type != TYPE_BEGIN)
{
pos = -1;
}
}
if(!strLine.isEmpty())
strList.append(strLine);
}
QFile outFile(QString("%1/Src/%2")
.arg(QApplication::applicationDirPath())
.arg(fileName.split('/').last()));
if(!outFile.open(QIODevice::WriteOnly))
{
AppendLog(tr("新建文件失败!"));
continue;
}
QTextStream out(&outFile);
out.setCodec("UTF-8");
out.setGenerateByteOrderMark(true);
foreach (QString str, strList)
{
out << str << endl;
}
}
ui->progressBar->setVisible(false);
完整项目见附件