使用Qt替换C++中文件中的文本
Replacing a text in file in C++ using Qt
我正在使用Qt库,并试图更改文件的内容。我想用fname替换存储在tok2中的文本。更新代码:
QFile file(destPath);
if (file.open(QIODevice::ReadWrite | QIODevice::Text))
{
QTextStream stream(&file);
while (!stream.atEnd())
{
QString line = stream.readLine();
QStringList tokenList = line.split("t");
if ( tokenList.count() == 2 && (tokenList.at(0).endsWith("FILE",Qt::CaseInsensitive)))
{
QString tok1 = tokenList.at(0).trimmed();
QString tok2 = tokenList.at(1).trimmed();
QFileInfo relPath(tok2);
QString fname = relPath.fileName();
QString newLine = tok1.append(" ").append(fname);
QString oldLine = tok1.append(" ").append(tok2);
qDebug() << "Original line: " << oldLine << "New line" << newLine;
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine();
QString outline = line.replace(QString(oldLine), QString(newLine));
in << outline;
}
}
}
}
}
tok2的原始内容格式为/something/filename.ext和我必须用filename.eext替换它,但上面的代码并没有用fname替换tok2的内容,简而言之,我无法在这个文件中写入。
你把事情搞得太复杂了。
const QString doStuff(const QString &str)
{
// Change string however you want
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
const QString filePath = "/home/user/test.txt";
QTextCodec *codec = QTextCodec::codecForLocale();
// Read file
QFile file(filePath);
if (!file.open(QFile::ReadOnly)) {
qDebug() << "Error opening for read: " << file.errorString();
return -1;
}
QString text = codec->toUnicode(file.readAll());
file.close();
text = doStuff(text);
// Write file
if (!file.open(QFile::WriteOnly)) {
qDebug() << "Error opening for write: " << file.errorString();
return -2;
}
file.write(codec->fromUnicode(text));
file.close();
return 0;
}
如果您的文件大小小于RAM的大小,则工作速度足够快。
我的解决方案非常适合我:
// Open file to copy contents
QFile file(srcPath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
// Open new file to write
QFile temp(destPath);
if (temp.open(QIODevice::ReadWrite | QIODevice::Text))
{
QTextStream stream(&file);
QTextStream out(&temp);
while (!stream.atEnd())
{
QString newLine;
//do stuff
out << newLine << "n";
}
temp.close();
}
file.close();
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入