1

在我的程序中,我试图通过制作几个小部件来处理几个页面。

在其中一个页面中,我想获取 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();
           }

}
4

2 回答 2

0

下面是如何从文件中读取的一个非常基本的示例。对“文件 IO 和 Qt”进行快速 google 会返回大约一百万个示例以及有关如何执行此类操作的说明。祝你好运。

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();
于 2013-06-15T23:53:20.467 回答
0

尝试关闭您写入的文件,以确保所有数据都刷新到磁盘。

users_file.close();
于 2013-06-15T10:55:58.877 回答