在我的程序中,我试图通过制作几个小部件来处理几个页面。
在其中一个页面中,我想获取一个ID,用户名和密码,并将它们存储在一个文件中。我可以毫无问题地做。
但是在另一个.cpp文件中我想使用存储在这些文件中的信息来查看输入的用户名和密码是否正确。但是我无法打开我已经制作过的文件并阅读它们。
所以我非常感谢有关如何打开和使用已经制作的文件并在其中包含文本的帮助。
我已经设法编写的用于存储信息的内容是:
QFile users_file; // making a file
QString ID= ui->IDlineEdit->text(); // storing what is written in the LineEdit in a QString
QString username= ui->UserlineEdit->text();
QString password= ui->PasslineEdit->text();
users_file.setFileName(ID); //the file's name will be the ID
users_file.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream users_fileStream(&users_file);
users_fileStream.operator <<(ID);
users_fileStream.operator <<("\n");
users_fileStream.operator <<(username);
users_fileStream.operator <<("\n");
users_fileStream.operator <<(password);
users_fileStream.operator <<("\n");
//and this is what I've written for opening the files and reading them.
// but i have to mention that this part is in another .cpp different from the
// one that i wrote my previous code in it.
// i know it doesn't work but that's all i could think of so far.
int i=1;
while( i)
{
QString username= ui->lineEdit->text();
QFile myfile;
myfile.setFileName(username);
myfile.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream files(&myfile);
QString PassFromFile;
// I've written this part twice because the password is actually the second line on my file.
PassFromFile=files.readLine();
PassFromFile=files.readLine();
if( PassFromFile == ui->lineEdit_2->text())
{ i=0;
this->centralWidget()->hide();
usersPage->show();
}
}
答案 0 :(得分:0)
尝试关闭您写入的文件,以确保将所有数据刷新到磁盘。
users_file.close();
答案 1 :(得分:0)
以下是如何从文件中读取的一个非常基本的示例。快速谷歌“文件IO和Qt”返回了大约一百万个例子和解释如何做这些事情。祝你好运。
QFile file("pathToSomeFile/someFile.txt");
if(!file.open(QIODevice::ReadOnly))
QMessageBox::information(0, "Error", file.errorString());
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
// Do whatever you want to do with this data here
// We're reading in one line of text from the file at a time
}
file.close();