Qtで別の問題が発生しました。テキストファイルの特定の行に。を使用して書き込む方法がわからないようですQFile
。代わりに、最初に書かれたすべてが消去されます。それで、与えられた情報で、私はどのように特定の行に書くのでしょうQFile
か?
ここに2つの機能があります。
- 最初の関数はファイルを検索し、次に2つの変数を取得します。次の空の行を見つけるもの、現在のID番号を取得するもの。
- 2番目の関数は書き込むことになっています。しかし、私は必要なものに関するドキュメントを探しました。それをグーグルで検索し、多くの検索を試みましたが、役に立ちませんでした。
機能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
そして、この関数は、私が必要だと思った2ビットの情報を取得します。私はあまり精通しておらず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」に置き換えることだけです。
誰かが特定の行に書き込む方法を知っていますか、または少なくともファイルの最後に移動してから書き込む方法を知っていますか?