Replacing a text in file in C++ using Qt -
i using qt library , trying change contents of file. want replace text stored in tok2 fname. updated code:
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; } } } } }
original contents of tok2 in format ../something/filename.ext , have replace filename.ext above code not replacing contents of tok2 fname, in short unable write in file.
you making things complicated.
const qstring dostuff(const qstring &str) { // change string 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 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 write: " << file.errorstring(); return -2; } file.write(codec->fromunicode(text)); file.close(); return 0; }
works fast enough, if file size less amount of ram.
Comments
Post a Comment