Listing Directory Entries with Qt on Remote Windows Server - qt

I am on a Windows Server which is in the same network as the Server with the computer name service.
I got this simple code which tries to list the content
QFileInfoList fiList = QDir("\\service\\Documents").entryInfoList(QDir::Files);
qDebug() << "sizeof filist: " << fiList.size();
for (const QFileInfo& fi : fiList)
{
qDebug() << fi.absoluteFilePath();
}
The output is the following:
sizeof filist: 0
I make sure that the folder is shared on the network by checking the properties and also using the windows explorer. I can access the folder via Windows Explorer.
Is the functionality I am trying to achieve not possible with QDir?

It turns out there are 2 backslashes more needed because \ needs to be escaped.
So the right code would be:
QFileInfoList fiList = QDir("\\\\service\\Documents").entryInfoList(QDir::Files);
qDebug() << "sizeof filist: " << fiList.size();
for (const QFileInfo& fi : fiList)
{
qDebug() << fi.absoluteFilePath();
}

Related

finding connected Wifi network

I'm using Ubuntu 18.04.
How do I retrieve the name of the WiFi that the system is connected to. So far I'm querying with the following but it is returning interface names instead of Wifi names:
QNetworkConfigurationManager nwkMgr;
QList<QNetworkConfiguration> nwkCnfList = nwkMgr.allConfigurations();
for(const QNetworkConfiguration &ncnf : nwkCnfList)
{
qDebug() << ncnf.name() << ncnf.bearerType();
if (ncnf.bearerType() == QNetworkConfiguration::BearerWLAN)
{
// would like to detect WiFi here
qDebug() << "WiFi:" << ncnf.name();
}
}
This lists the interfaces:
"Wired connection 1" 1
"ens33" 1
How can I get the NAME of the Wifi?
Can you use system variables ? If so do this:
export WNAME=$(iw dev | grep ssid | awk '{print $2}')
It will export it to a variable WNAME and you can use it inside scripts untill you logout or shutdown the system.

Qt: cannot open file for writing

I try to access a simple text file from a Qt-widget application with the QFile class for reading an writing. Reading the file line by line as a string works fine. But opening it ready to write fails. The following code checks if the file exists and tries to set the proper permissions, but in the end the file won't open.
Here is the failing piece of code:
#include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[]){
QApplication app(argc, argv);
MainWindow w;
w.show();
QFile file(":/test.dat");
qDebug() << "exists? " << file.exists();
qDebug() << "writable? " << file.isWritable();
qDebug() << "permissions before? " << file.permissions();
qDebug() << "permissions set? " << file.setPermissions(QFileDevice::WriteOther | QFileDevice::ReadOther);
qDebug() << "permissions after? " << file.permissions();
qDebug() << "opened? " << file.open(QIODevice::Append);
qDebug() << "errors? " << file.errorString();
qDebug() << "errnum? " << file.error();
QTextStream out(&file);
out << "something to append";
file.close();
return app.exec();
}
Qt returns this message:
exists? true
writable? false
permissions before? QFlags(0x4|0x40|0x400|0x4000)
permissions set? false
permissions after? QFlags(0x4|0x40|0x400|0x4000)
opened? false
errors? "Unknown error"
errnum? 5
QIODevice::write (QFile, ":/test.dat"): device not open
If I change the parameter in the open-function to QIODevice::ReadOnly the file is readable without problems, failing with QIODevice::WriteOnly. Why doesn't the same thing work for writing as well? Is it the permission? And why don't the permissions change after I called setPermissions? I run Qt as root on Ubuntu 14.04. And test.dat has full rights -rwxrwxrwx owned by user.
Can someone help?
Thanks!
The author is having Linux-related problem with writing to file created by console process with elevated privileges. I have fully reproduced the problem and when attempted to remove the file with:
vi \home\myuser\Documents\f.txt // create file like that from console
rm \home\myuser\Documents\f.txt // now try to remove it from console
I got "rm: remove write-protected regular file "\home\myuser\Documents\f.txt" and responded "yes" and then the code above shows after creating new file in the context of the program's process:
opened? true
exists? true
writable? true
permissions before? QFlags(0x4|0x20|0x40|0x200|0x400|0x2000|0x4000)
permissions set? true
permissions after? QFlags(0x4|0x20|0x40|0x200|0x400|0x2000|0x4000)
errors? "Unknown error"
errnum? 0
I run Qt Creator as root on Ubuntu 14.04.
It does not ensure the privileges of the program you run from it, I guess. UPDATE: make sure you run the program with appropriate permissions e.g. Root in this case.

Files getting corrupted when being downloaded using QNetworkAcessManager

I'm developing a client app whose purpose is to download some files from a web server, temporarily store them in the Temp folder, check for file integrity, then send them to a FTP server in a Embedded Linux device.
Recently I got problems when doing the process in a preliminary development stage when I was trying to do the download from my local machine (see related question here). Now I'm able to download and upload without errors and with verification (I'm using QCryptographicHash + file size to check for any nonconformities) from my machine, but the same doesn't happen when I try downloading from the HTTP server.
There is a total of 8 files being downloaded: three .tar.gz, one simple text, two programs and two binaries. I'm able to successfully download all compressed files, the text file and one of the binaries, but the others, namely the two programs and one of the binaries (a Linux Kernel image) are always being incorrectly downloaded.
I check this by noticing not only that the hash returns error for them, but also for their sizes: their sizes are always wrong (and always the same erroneous value for any download attempt). And the files in the server are all correct.
My first suspicion was that I need to configure the HTTP download in a way that differs from the common FTP download from the local machine, but I'm unaware on how would that be. Moreover if this extra configuration was needed, then why some of the files always return correctly?
Here is the relevant code as for now:
void MainWindow::processNextDownload()
{
QUrl ulrTemp(updateData.at(transferStep).downloadUrl.arg(ui->leID->text())); //"//" +
if (updateData.at(transferStep).downloadUrl.contains("http"))
ulrTemp.setScheme("http");
else
ulrTemp.setScheme("file");
// ulrTemp.setUserName();
// ulrTemp.setPassword();
// ulrTemp.setPort();
qDebug() << "Downloading" << transferStep << "from" << ulrTemp;
#if 1
poReply = downloadNetworkManager->get(QNetworkRequest(ulrTemp));
#else
QNetworkRequest request;
request.setUrl(ulrTemp);
request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17");
poReply = downloadNetworkManager->get(request);
#endif
connect(poReply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(slotDownloadProgress(qint64,qint64)));
ui->statusBar->showMessage(tr("Downloading: %1").arg(updateData.at(transferStep).itemName));
}
void MainWindow::slotFileDownloaded(QNetworkReply* reply)
{
if (reply && (reply->error() != QNetworkReply::NoError))
{
ui->statusBar->clearMessage();
if (!isSingleFile)
{
const QString strTemp = tr("An error occurred while downloading \"%1\": %2 (error message: %3)")
.arg(updateData.at(transferStep).downloadName).arg(reply->error()).arg(reply->errorString());
QMessageBox::critical(this,tr("Error in download"),strTemp);
}
else
{
//irrelevant...
}
finished(false);
return;
}
qDebug() << "To write: " << reply->bytesAvailable();
QByteArray downloadedData = reply->readAll();
reply->deleteLater();
poReply->deleteLater();
//![]
static const QString tempFilePath = QDir::tempPath();
if (!isSingleFile)
{
QFile file(tempFilePath + "/" + updateData.at(transferStep).downloadName);
if (!file.open(QFile::WriteOnly | QFile::Truncate))
{
qDebug() << "Failure opening temp file to write: " << file.fileName();
QMessageBox::critical(this,
tr("Error"),
tr("An error occured while trying to open a temporary file to write the downloaded data (file: %1).").arg(file.fileName()));
transferStep = downloadStepCount;
slotFileUploaded(NULL);
return;
}
qint32 bytesWritten = file.write(downloadedData);
file.flush();
if (downloadedData.size() != bytesWritten)
qDebug() << "Write failed, wrote" << bytesWritten << "out of" << downloadedData.size() << "bytes.";
else
qDebug() << "Wrote " << bytesWritten << "bytes.";
file.close();
//![]
if (++transferStep >= downloadStepCount)
{
qDebug() << "Start hash check";
slotStartHashCheck();
return;
}
processNextDownload();
}
else
{
//irrelevant...
}
}
And this is why I get (the last number value after the "=" in the hash code is the file size):
So what am I missing?

Qt: QUrl::fromUserInput intepretes FTP Url wrong

I have some issue in passing a FTP string into QUrl:
std::cout << QUrl::fromUserInput("ftp://user#host.com:password#ftphost:21/path/file.ext").toString().toStdString().c_str() << std::endl;
Is always resulting in
http://ftp//user#host.com:password#ftphost:21/path/file.ext
which is obviously wrong. What's the problem with the above FTP Url? Or is that a known issue within Qt4?
I am working on Linux, using Qt 4.8.1.
Even following code
if(QUrl("ftp://user#host.com:password#ftphost:21/path/file.ext").isValid())
std::cout << "is valid" << std::endl;
else
std::cout << "is not valid" << std::endl;
Is resulting in "is not valid"
Thanks in advance
You need manually replace # in username with %40. That's what QUrl does internally if QUrl::setUserName() is called with user#domain.tld.

Qt endl looks great from linux telnet, wrong from windows telnet

I am building a telnet server app in Qt, and when I connect from a linux telnet client output looks great. For example, sending "A" << endl << "B" << endl << "C" to my console looks like:
A
B
C
Now when I connect from a Windows telnet client I see
A
B
C
obviously Qt's endl is sending only '\n'. Is there a SIMPLE solution to this? If I replace endl with "\r\n" do I mess up linux clients now? Do I have to force a flush too?
Here is actual code I am using to send to my telnet client:
QString block;
QTextStream out(&block, QIODevice::WriteOnly);
out << "Valid commands are: " << endl
<< " help Print this list" << endl
<< " version Print this version" << endl
<< " clientcount Show the number of active telnet clients" << endl
<< " logrotate Rotate the event log file" << endl
<< " shutdown Initiate shutdown secast" << endl
<< " quit Disconnect your telnet session" << endl
<< " stop Shutdown secast" << endl;
tcpSocketPtr->write(block.toUtf8());
You could simply drop the QTextStream and write the QString directly in here:
QString block = QString("Valid commands are: \n")
+ " help Print this list\n"
+ " version Print this version\n"
+ " clientcount Show the number of active telnet clients\n"
+ " logrotate Rotate the event log file\n"
+ " shutdown Initiate shutdown secast\n"
+ " quit Disconnect your telnet session\n"
+ " stop Shutdown secast\n";
tcpSocketPtr->write(block.toUtf8());
Based on your comment though, you seem to use some old DOS client (on Windows!) which expects "\r\n". In that case, I would send "\r\n" for that, but only the usual "\n" for Linux. It is a not so good practice to send carriage return as well on Linux, and not just line feed even though "\r\n" may seem to work on Linux.

Resources