QFile file(filepath);
if (!file.open(QIODevice::ReadOnly)) {
qWarning() << "DetectImageFormat() failed to open file:" << filepath;
return "";
}
const QByteArray data = file.read(1024);
// Check svg file. but sometimes i get the data failed!
if (data.indexOf("<svg") > -1) {
return "svg";
}
void write(QString filename) {
QChar ch('b');
QFile mfile(filename);
if (!mfile.open(QFile::WriteOnly) {
qDebug() << "Could not open file for writing";
return;
}
QDataStream out(&mfile);
out.setVersion(QDataStream::Qt_4_8);
out << ch;
mfile.close();
}
open binary file and writing 'b'(binary)
void read(QString filename) {
QFile mfile(filename);
if (!mfile.open(QFile::ReadOnly)) {
qDebug() << "Could not open file for reading";
return;
}
QDataStream in(&mfile);
in.setVersion(QDataStream::Qt_4_8);
QChar mT;
in >> mT;
qDebug() << mT;
mfile.close();
}
read but not mT='b'.if ch and mT variables are int always mT=4 why?How can i writing ch(binary file) and read from binary file
the 4 number is the length of your data. QDataStream store length of your data before it to indicate how many bytes need to read to gain the written data. your data has been written after it.
I have a treeview that displays a folder with text files. There is a 'open' button. That will open the file. But when this button is pressed it should rename the file to: read filename.txt. So if there is a file for example that is name nameslist.txt and the button is pressed it should rename it to read nameslist.txt or something similar. I thought of something like this:
void berichtenhistorie::on_Openbutton_released()
{
QModelIndex index = ui->treeView->currentIndex();
QString name = index.fileName();
QString path = index.filePath();
QFile file(path);
file.open(QIODevice::WriteOnly | QIODevice::Text);
file.rename("read " + name);
file.close();
}
But this isnt working. I get the following error's:
error: C2352: 'QDirModel::fileName' : illegal call of non-static member function
But I dont know how to use fileName() and filePath() correctly.
Thanks for help!
I think that here is what you looking for:
void berichtenhistorie::on_Openbutton_released()
{
QModelIndex index = ui->treeView->currentIndex();
QFileSystemModel *model = (QFileSystemModel*)ui->treeView->model();
QString path = model->filePath(index);
QString name = model->fileName(index);
QString dir = path;
dir.remove(dir.size() - name.size(), name.size());
QFile file(path);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
//Interact with the file
file.close();
if(file.rename(QString("%1read %2").arg(dir, name)))
qDebug() << "Renamed";
}
}
Here's a break out of each step you'll need to do to work with QFile.
QFile file("test.txt");
if(file.exists())
{
qDebug() << "found file";
if(file.open(QIODevice::ReadWrite))
{
qDebug() << "opened";
if(file.rename("text1.txt"))
{
qDebug() << "renamed";
}
else
{
qDebug() << "failed to rename";
}
file.close();
}
}
else
{
qDebug() << "file does not exist";
}
In the end, you'll only really need your debugger to step through instead of printing out everything known to your application. E.g.
QFile file("test.txt");
if(file.exists() && file.open(QIODevice::ReadWrite))
{
if(file.rename("text1.txt"))
{
qDebug() << "renamed";
}
file.close();
}
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();
I have this QT script using webkit. I can download files no problem but I can't get the progress bar moving in the file dialog. I think the network reply has already been sent before I call the progress dialog as there is a delay from clicking the download link and then then qDebug() << "Left click - download!"; being echo's out into console. How can I intercept the netwrok reply before it has finished and the unsupportedContent() method is called?
EDIT:
I could strip it out and use reply = manager.get(QNetworkRequest(url)); but I don't actually know the URL it could be any link the user clicks, there is no predefined URL?
void MainWindow::unsupportedContent(QNetworkReply *reply) {
qDebug() << "Left click - download!";
qDebug() << "Bytes to download: " << reply->bytesAvailable();
QString str = reply->rawHeader("Content-Disposition");
QString end = str.mid(21);
end.chop(1);
qDebug() << "File name: " << end;
qDebug() << "File type: " << reply->rawHeader("Content-Type");
qDebug() << "File size (bytes): " << reply->bytesAvailable();
QString defaultFileName = QFileInfo(end).fileName();
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
if (fileName.isEmpty()) return;
file = new QFile(fileName);
if(!file->open(QIODevice::WriteOnly))
{
QMessageBox::information(this, "Downloader",
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
file = NULL;
return;
}
downloadRequestAborted = false;
connect(reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
connect(reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
progressDialog->setLabelText(tr("Downloading %1...").arg(fileName));
//downloadButton->setEnabled(false);
progressDialog->exec();
//QFile file(fileName);
//file.open( QIODevice::WriteOnly );
//file.write(reply->read(reply->bytesAvailable()));
//file.close();
}
void MainWindow::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
qDebug() << bytesReceived << bytesTotal;
if(downloadRequestAborted)
return;
progressDialog->setMaximum(bytesTotal);
progressDialog->setValue(bytesReceived);
}
void MainWindow::downloadReadyRead()
{
if(file)
file->write(reply->read(reply->bytesAvailable()));
}
void MainWindow::downloadFinished()
{
qDebug() << "Download finished!";
if(downloadRequestAborted)
{
if(file)
{
file->close();
file->remove();
delete file;
file = NULL;
}
reply->deleteLater();
progressDialog->hide();
//downloadButton->setEnabled(true);
return;
}
downloadReadyRead();
progressDialog->hide();
//downloadButton->setEnabled(true);
file->flush();
file->close();
if(reply->error())
{
//Download failed
QMessageBox::information(this, "Download failed", tr("Failed: %1").arg(reply->errorString()));
}
reply->deleteLater();
reply = NULL;
delete file;
file = NULL;
}
void MainWindow::cancelDownload()
{
downloadRequestAborted = true;
reply->abort();
progressDialog->hide();
//downloadButton->setEnabled(true);
}
The above method was working the whole time the problem was the bytes it was receiving was so small you could not tell it had downloaded at all, once I attempted to download a larger file the bytes being downloaded were adequately displayed :)
Here is the method I ended up with that could receive a request and save it disk.
void MainWindow::unsupportedContent(QNetworkReply *reply) {
QString str = reply->rawHeader("Content-Disposition");
QString end = str.mid(21);
end.chop(1);
QString defaultFileName = QFileInfo(end).fileName();
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
if (fileName.isEmpty()) return;
file = new QFile(fileName);
if(!file->open(QIODevice::WriteOnly))
{
QMessageBox::information(this, "Downloader",
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
file = NULL;
return;
}
downloadRequestAborted = false;
if(!reply->isFinished()){
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), SLOT(downloadProgress(qint64, qint64)));
connect(progressDialog, SIGNAL(canceled()), SLOT(cancelDownload()));
progressDialog->setLabelText(tr("Downloading %1...").arg(fileName));
progressDialog->exec();
//return;
}
if(downloadRequestAborted)
{
if(file)
{
file->close();
file->remove();
delete file;
file = NULL;
}
reply->abort();
reply->deleteLater();
progressDialog->hide();
return;
}
file->write(reply->read(reply->bytesAvailable()));
file->flush();
file->close();
file = NULL;
if(file == NULL){
isDownload = true;
fileURL = fileName;
systray->showMessage("CytoViewer v1.0", "Download finished - Click to open", QSystemTrayIcon::NoIcon, 10000);
}
}