Qt,Q文件写入特定行
Qt, QFile write on specific line
我在Qt中遇到了另一个问题,我似乎不知道如何用QFile
在文本文件的特定行上书写。相反,所有的东西都在一开始就被抹去了。那么,对于给定的信息,我将如何在QFile
中写入特定的行呢?
这里有两个函数。
- 第一个函数搜索一个文件,然后得到两个变量。一个查找下一个空行的,一个获取当前ID号的
- 第二个函数应该是写的。但我一直在寻找我需要的文件,我在谷歌上搜索了它,并尝试了多次搜索,但都无济于事
功能1
QString fileName = "C:\Users\Gabe\SeniorProj\Students.txt";
QFile mFile(fileName);
QTextStream stream(&mFile);
QString line;
int x = 1; //this counts how many lines there are inside the text file
QString currentID;
if(!mFile.open(QFile::ReadOnly | QFile::Text)){
qDebug() << "Could not open file for reading";
return;
}
do {
line = stream.readLine();
QStringList parts = line.split(";", QString::KeepEmptyParts);
if (parts.length() == 3) {
QString id = parts[0];
QString firstName = parts[1];
QString lastName = parts[2];
x++; //this counts how many lines there are inside the text file
currentID = parts[0];//current ID number
}
}while (!line.isNull());
mFile.flush();
mFile.close();
Write(x, currentID); //calls function to operate on file
}
上面的函数读取的文件如下所示。
1001;James;Bark
1002;Jeremy;Parker
1003;Seinfeld;Parker
1004;Sigfried;FonStein
1005;Rabbun;Hassan
1006;Jenniffer;Jones
1007;Agent;Smith
1008;Mister;Anderson
这个函数得到了两个我认为可能需要的信息。我不太熟悉QFile
和搜索,但我想我需要这些变量:
int x; //This becomes 9 at the end of the search.
QString currentID; //This becomes 1008 at the end of the search.
所以我把这些变量传递给下一个函数,在函数1的末尾。Write(x, currentID);
功能2
void StudentAddClass::Write(int currentLine, QString idNum){
QString fileName = "C:\Users\Gabe\SeniorProj\Students.txt";
QFile mFile(fileName);
QTextStream stream(&mFile);
QString line;
if(!mFile.open(QFile::WriteOnly | QFile::Text)){
qDebug() << "Could not open file for writing";
return;
}
QTextStream out(&mFile);
out << "HelloWorld";
}
我已经省去了自己修复这个问题的任何尝试,这个函数所做的只是用"HelloWorld"替换文本文件的所有内容。
有人知道如何在特定的行上写吗,或者至少到文件的末尾再写吗?
如果要插入文件的行始终是最后一行(如函数1所示),则可以尝试在Write方法中使用QIODevice::append以追加模式打开文件。
如果你想在文件中间插入一行,我想一个简单的方法是使用一个临时文件(或者,如果可能的话,将行加载到QList中,插入行并将列表写回文件)
QString fileName = "student.txt";
QFile mFile(fileName);
if(!mFile.open(QFile::Append | QFile::Text)){
qDebug() << "Could not open file for writing";
return 0;
}
QTextStream out(&mFile);
out << "The magic number is: " << 4 << "n";
mFile.close();
上面的代码片段将在文件末尾附加文本"神奇的数字是:4"。
相关文章:
- 如何在cpp文件之间切换窗口?在Qt中
- Qt 5.11.2 (Clang 8.0 (Apple), 64 位), 找不到 QJSEngine 文件
- 使用 Bazel 生成 QT 资源文件
- Qt C++:不同文件中同一命名空间的多个Q_NAMESPACE
- 如何识别项目是 QT 中的文件还是文件夹
- 使用 Cmake 在 Qt Creator 中显示头文件
- 如何将网络模块添加到 QT pro 文件中?
- 如何在 qt for windows 中使用 QAxObject 创建 docx 和 doc 文件?
- 如何将 json 数据附加到 Qt 中的现有 json 文件中
- 如何在 CMakeLists.txt Qt Creator 中包含头文件?
- cmake:构建依赖于非源文件.Qt帮助生成
- 如何从 txt 文件 - Qt 中读取特定行
- QIODevice::read:设备未打开远程JSON文件QT
- 在iOS设备上找不到文件QT创建者C QstandardPaths :: StandardLocations(Qs
- 将长字符流写入文本文件QT C++
- 删除单行文本文件QT
- 在.pro文件QT中定义带有转义字符的字符串宏
- 复制多个文件段到一个文件- Qt
- 编译 moc 文件 Qt 4.5.2 intrin.h 意外类型 "void" Visual Studio 2015
- 文件输入-未读取的文件QT