Writing to file in Qt - qt

I have a problem with writing to file, the problem is :
If I write the directory ":/Files/Scores.txt" it won't write anything but it reads from same directory.
But if I used this directory "D:/TicTacToe/TicTacToe/Scores.txt" it writes and reads but i will give the game to my instructor and the path won't be same and the file won't open, any ideas ?!
My write code:
void Write ( QString file)
{
QFile sfile(file);
if(!sfile.open(QFile::ReadOnly |QFile::Text))
{
return;
}
QTextStream in(&sfile);
QString lscores =sfile.readAll() ;
sfile.close();
if(!sfile.open(QFile::WriteOnly |QFile::Text))
{
return;
}
lscores=" "+Xscore+"\t"+" "+Oscore+"\n"+lscores;
QTextStream out(&sfile);
out <<lscores;
sfile.close();
}

Resource files (the ones you put in .qrc file) are read only, as MrEricSir mentioned. If you want to have some configuration/score file with your app you can for example use QApplication::applicationDirPath()
QString settingsFile = QApplication::applicationDirPath() % QLatin1Literal("/scores.txt");
This way you will have always absolute path to the file inside your app directory.
You can also use QDesktopServices::storageLocation with QDesktopServices::DataLocation parameter to obtain data location for your application.

Related

Qt5.12.0 relative path doesn't work but absolute path works

I'm using Qt5.12.0 on macOS Catalina 10.15.6.
I can load files using absolute path, but can't do that using relative path. However, I want to use the relative path to robust the code. I think the absolute path is not maintainable as relative path.
I have tried QDir::currentPath();, QApplication::applicationDirPath(), and QCoreApplication::applicationDirPath(); but they all give me the absolute path.
Below are loadPhotos, so far, only the print dir.entryList(QDir::Files) part is used.
// load photo cantainer
void TimerDialog::loadPhotos(const QString &path)
{
qDebug() << "in func loadPhotos, path is: " << path;
// in func loadPhotos, path is: "./images"
// QDir dir("");
QDir dir(path);
// trevase current directory
QStringList fileList = dir.entryList(QDir::Files);
qDebug() << "in func loadPhotos, fileList is: " << fileList;
// TODO in func loadPhotos, fileList is: ()
for (int i=0; i<fileList.size();i++) {
QImage image(path+"/"+fileList.at(i));
qDebug() << "fileList.at(i): " << fileList.at(i);
m_vecPhotos << image;
}
QStringList folderList = dir.entryList(QDir::Dirs|
QDir::NoDotAndDotDot);
for (int i = 0; i < folderList.size(); ++i) {
loadPhotos(path+"/"+folderList.at(i));
}
}
I put images folder under the project file, which is bili_tedu_timer. There are 20 pictures in the images folder.
I have disabled Shadow build in Projects mode
I tried qmake in Qt creator, but it still doesn't work #ניר
It is truth that if the absolute path works, the relative path will work. The question is, where is the current directory?
I've implemented three kinds of ways to see where the current directory is. But I am unaware that the current directory is MacOS, which is not project directory bili_tedu_timer, where I put images folder.
From the current Path output,bili_tedu_timer is THREE level upper than MacOS, so use ../../../ to get to the correct folder.
Actually, it's quite straightforward. But as a beginner as me, I don't have the sensitive about the program. What I did was I save a file (Thx to my roommate, she told me this method) to find out where I am, reference. Without surprise, I am in MacOS. I suddenly realized that I was so close to the solution.

QSettings of ini file from internet

Im using this function so far:
bool MSSQL::checkSettings()
{
QString settingsFile = "someDir/setup.ini";
QString fileName(settingsFile);
QFile file(fileName);
if(QFileInfo::exists(fileName)) {
return true;
}
else {
qDebug() << "Error: No INI File Found on path:" << settingsFile;
return false;
}
}
which works fine.
However when I wish to use an online ini file which is reachable (because can be opened via browser link), then its a false, for example if i use:
QString settingsFile = "http://localhost/something/setup.ini";
which QT should be able to read, then it doesnt work...
any ideas?
I dont see where you are using QSettings at all. You are using QFile, which is representation of a local file.
To your question:
QSettings does not able to read/write setting from URL. You have to download it manually before instantiating QSettings, See QNetworkAccessManager.
Or you may try to make your own settings provider, by using: QSettings::registerFormat() static function.

QDir::rename returns false

I would like to transfer a file from a certain directory to another, But when i use QDir. rename it seems to always fail.
void handler::moveToTempFolder(QString localFilePath)
{
qDebug()<<localFilePath; <--- "C:/Users/user1/Pictures/IMG_00000009.jpg"
qDebug()<<"/TempFiles/" + getFileNameFromPath(localFilePath); <---- "/TempFiles/IMG_00000009.jpg" a folder that is in the same location as the .pro
QDir dir;
if(dir.rename(localFilePath,"/TempFiles/" + getFileNameFromPath(localFilePath)))
qDebug()<<"Success";
else
qDebug()<<"Failed";
}
I am getting Failed on my terminal. can anybody help?
Qt does not have a method to access the project folder that you .pro file is in. Probably because once you deploy this, any device other than yours will not have that folder.
It can however access the folder where the executable is with QDir::currentPath().
Also, I'm not sure how you defined getFileNameFromPath - but you can do that with QFileInfo.
void MainWindow::moveToTempFolder(QString localFilePath)
{
QFileInfo fileInfo(localFilePath);
QDir dir;
QString tempFilePath = dir.currentPath() + "/TempFiles/" + fileInfo.fileName();
if(dir.rename(localFilePath, tempFilePath))
{
qDebug() << "Success";
} else {
qDebug() << "Failed";
}
}
Note: When you run this from Qt Creator, your /TempFiles/ folder will most likely be in the same folder as your /debug/ and /release/ folders (one level up from your executable). But once you deploy this (or run it manually from the .exe) - /TempFiles/ will be in the same folderas the .exe
The working directory while the program is running is the build folder, not the project folder. My guess would be that is your problem.

how to get list of files stored in a .qrc Qt Resorce file?

I'm very new to Qt..and in my program i have added some icon files in .qrc resource file.
How can we list in our program the files stored in qrc ?
Here's example code that should do it:
QDirIterator it(":", QDirIterator::Subdirectories);
while (it.hasNext()) {
qDebug() << it.next();
}
Link to documentation:
http://doc.qt.io/qt-5/qdiriterator.html

QFtp download location issue

I just wrote tiny ftp client using Qt. The problem is when I download, the ftp->get() command downloads the file to the default location. I'd like to define a path where the downloaded file will go.
This is my DownloadFile method:
QString fileName = fileListTreeWidget->currentItem()->text(0);
if (QFile::exists(fileName)) {
QMessageBox::information(this, tr("FTP"),
tr("There already exists a file called %1 in "
"the current directory.").arg(fileName));
return;
}
file = new QFile(fileName);
if (!file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("FTP"),
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
return;
}
ftp->get(fileListTreeWidget->currentItem()->text(0), file);
Just create the file object with the path you want and QFtp will save there. Something like;
file = new QFile(QString("/path/to/download/%1").arg(fileName));

Resources