C++ Qt - opening text file operation failure - c++

I'm using Qt to develop my C++ application using QML as well.
Here's my code
QFile inputFile("data.txt");
//QFile inputFile("/:data.txt");
qDebug() << "Hello:";
if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Wasn't ready:";
}
else{
qDebug() << "Txt file ready:";
QTextStream in(&inputFile);
while ( !in.atEnd() )
{
QString line = in.readLine();
qDebug() << "message: " << line;
}
}
I was wondering why it doesn't work. The console always prints "Wasn't ready".
Please help.

In the error handling block where you do qDebug() << "Wasn't ready:"; you should call inputFile.error() and print out the returned value to get more details of what went wrong.
It might also be an idea to start the program with printing out the current directory, to make sure that the file is searched for in the correct location.

Related

How to read from QFile? It shows that file not accessible

I've been trying to read .xml file using QFile. But qt creator can't even find it, but file exists inside project (also I tried to read it from another directory, not project's, it doesn't work, too). Debuger says file not accessible.
Here's my code:
QFile file("../info.xml");
if (file.exists())
if (file.open(QFile::ReadOnly | QFile::Text))
qDebug(qPrintable("File exist"));
This is not a complete answer, but rather a list of what may have gone wrong.
Check the file path :
QFileInfo inf (file);
qDebug() << inf.QFileInfo::path();
Ensure that the file is in the right directory, i.e. in the same you have your .exe (build-ProjectName-...). You can check this by using QDir::currentPath()
Check which if causes the problem : is it the first one which checks file existence or the second one that cannot open it ?
I am not sure it is a good idea to use the QFile::Text for .xml files.
In the end, I would do something like this :
QFile file("../info.xml");
QFileInfo inf (file);
qDebug() << "File path : "<< inf.QFileInfo::path() << Qt::endl;
qDebug() << "Current path : " << QDir::currentPath() << Qt::endl;
qDebug() << "Current path (expected) : " << QDir::currentPath() + "/info.xml" << Qt::endl;
if (file.exists()){
qDebug() << "exists" << Qt::endl;
if (file.open(QFile::ReadOnly)){qDebug() << "opened";}
}

Do-while infinite loop in Qt

I'm trying to read in a file of trace addresses (each on their own line) and append to the front of each. This input file is intended to be the engine of a cache emulator i'm trying to build. I am having issues reading the file in without getting into an infinite loop. When I change the do-while to run on a false condition, I get the proper output for just the do segment. Therefore, I know I'm running into an infinite loop issue with how I worded my while segment. Maybe i'm fatigued and can't see the issue with this function:
void MainWindow::readFile(){
infoLabel->setText(tr("Invoked <b>File|Open</b>"));
QString filename="trace.txt";
QString path = QDir::currentPath();
QFile file("//Users//nathan1324//Desktop//trace.txt");
//file.open(QIODevice::ReadOnly);
if(!file.exists()){
qDebug() << "File cannot be found "<<filename;
qDebug() << " " << path;
}else{
qDebug() << filename<<" Opening...";
}
QString line;
textEdit->clear();
if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
QTextStream stream(&file);
do {
line = stream.readLine();
textEdit->setText(textEdit->toPlainText()+"0x"+line+"\n");
qDebug() << "line: "<<line;
} while (!line.isNull());
}
file.close();
}
Any suggestions of an alternative way to write this function?
To add items use the append function of QTextEdit:
void QTextEdit::append(const QString & text)
Appends a new paragraph with text to the end of the text edit.
Note: The new paragraph appended will have the same character format
and block format as the current paragraph, determined by the position
of the cursor.
To iterate through the QTextStream atEnd()
bool QTextStream::atEnd() const
Returns true if there is no more data to be read from the QTextStream;
otherwise returns false. This is similar to, but not the same as
calling QIODevice::atEnd(), as QTextStream also takes into account its
internal Unicode buffer.
Code:
void MainWindow::readFile(){
infoLabel->setText(tr("Invoked <b>File|Open</b>"));
QString filename = "trace.txt";
QString path = QDir::currentPath();
QFile file("//Users//nathan1324//Desktop//trace.txt");
if(!file.exists()){
qDebug() << "File cannot be found "<<filename;
qDebug() << " " << path;
return;
}
QString line;
textEdit->clear();
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "Could not open file" << filename;
return;
}
qDebug() << filename<<" Opening...";
QTextStream stream(&file);
while (!stream.atEnd()) {
line = stream.readLine();
if(!line.isNull()){
textEdit->append("0x"+line);
qDebug() << "line: "<<line;
}
}
file.close();
}
Use atEnd to detect the end of a stream:
bool QTextStream::atEnd() const
Returns true if there is no more data to be read from the QTextStream;
otherwise returns false. This is similar to, but not the same as
calling QIODevice::atEnd(), as QTextStream also takes into account its
internal Unicode buffer.
while (!stream.atEnd()) {
line = stream.readLine();
textEdit->setText(textEdit->toPlainText()+"0x"+line+"\n");
qDebug() << "line: "<<line;
}

Qt QFile return non existent but still opens and writes to file

I have this file which is located in my C drive, I know it exists. When I access it with QFile.exists() it returns false, however it still opens the file and writes to it, I just cant read it. I've been working on this for a while and cannot find a solution, any suggestions are appreciated.
QFile tmpfile("C:/file.txt");
QString tmpcontent;
if(!QFile::exists("C:/file.txt"))
qDebug() << "File not found"; // This is outputted
if (tmpfile.open(QIODevice::ReadWrite | QIODevice::Truncate)) {
QTextStream stream(&tmpfile);
stream << "test"; //this is written
tmpcontent = tmpfile.readAll(); // this returns nothing
}
If file is not exist it will be created by open because you do it in write mode.
readAll function return all remaining data from device, since you just write something you are currently at the end of a file, and there is no data, try to seek( 0 ) to return to the beginnig of a file and then use readAll.
qDebug() << "File exists: " << QFile::exists("text.txt");
QFile test( "text.txt" );
if ( test.open( QIODevice::ReadWrite | QIODevice::Truncate ) ){
QTextStream str( &test );
str << "Test string";
qDebug() << str.readAll();
str.seek( 0 );
qDebug() << str.readAll();
test.close();
}else{
qDebug() << "Fail to open file";
}
As I can see from your code you need that file as a temporary, in such case I suggest to use QTemporaryFile, it will be created in temp directory (I belive there will be no problem with permissions), with unique name and will be auto deleted in object dtor.

Qt (C++): QFile creates text file successfully but does not write to it

I have the following code, with which I am attempting to write to a file. When it is called, the file is created in the directory and the for-loop is entered. The values for in QVector<int> program also exist and are visible with qDebug(). However, after I close the file and the window, I check the file on my computer and it is completely empty. I have checked all over StackOverflow and the Qt forums and have yet to find a solution.
QString save_file = "C:/Users/MARVIN/Documents/Saddleback College/2015/Fall/CS3A/Semester Project/Emulator/hello.txt";
QFile file(save_file);
if(file.open(QFile::WriteOnly))
{
QTextStream out(&save_file);
out << "hello" << endl;
for(int i = 0; i < 100; i++)
{
out << program[i] << endl;
qDebug() << program[i] << endl;
}
file.close();
this->close();
}
Your issue:
QTextStream out(&save_file);
should be
QTextStream out(&file);

Qt reading from QTextStream

I'm trying to read a text file and display the contents in a QPlainTextEdit. Please can you point out what I'm doing wrong:
QFile jsonFile("data.json");
if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Failed to open file";
qDebug() << jsonFile.errorString();
return;
}
else
{
qDebug() << "File opened";
} //It returns that the file opened successfully
qDebug() << "File Exists?: " << jsonFile.exists(); //Yep, it exists.
QTextStream outStream(&jsonFile);
QString textString = outStream.readAll();
qDebug() << "Text string: " << textString; //textString is empty! ""
ui->fileToPost->setPlainText(textString); //fileToPost is the QPlainTextEdit
jsonFile.close();
If I do something like
QString textString = "The cat sat on the mat";
it displays fine. The problem is that nothing is being read from the stream (or maybe the file).
Try to check file's absolute path, probably it is not where, you expect it: qDebug()<<QFileInfo("data.json").absoluteFilePath();