PDA

View Full Version : fstream not working



MongKong
9th March 2020, 21:21
Hello
So i'm trying to read from a .txt file when the application is closed or when the user presses the X button on the top right corner.

I tried reading from a file that is already created, but for some reason it's not opening the file, it always prints out "doesn't exist".


void Game::closeEvent(QCloseEvent *event)
{
QString item;
/*
QFile inputFile("Save.txt");
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
item = in.readLine();
qDebug() << item;
}
inputFile.close();
}
*/
fstream myFile("Save.txt", ios::in);
string line;

//myFile.open("Save.txt");
if(myFile.is_open()){
while(getline(myFile,line)){
qDebug() << QString::fromStdString(line);
}

}else{
qDebug() << "doesnt exist";
}
myFile.close();
qDebug() << "closed";
}

I included <fstream>
and added using namespace std;
The file exists in the file and it contains 3 lines and each one of them has a string
And i tried both examples, using fstream and using QFile ( none of them work )

If anyone knows what could be the problem please help me out !

d_stranz
9th March 2020, 22:26
Your fstream declaration in line 17 assumes that the file is in your current working directory. You might be surprised to learn that the working directory may not be what you think it is. Add a call to the static method QDir::currentPath() and see if the return QString contains what you think it should.

MongKong
10th March 2020, 19:37
OOOOhhhh i see, i got it working so far i think, thank you very much !!!