Qfile open returns false - c++

I have kept the Content.xml in the same folder where my app.exe exists.
But open call returns false ?
What should be the exact path for the file ?
I do not want to give the complete path for the file but want my code to be path independent "means file which i want to read should be in same folder where my exe is lying"
#define FILE_NAME "Content.xml"
QString xmlFileName(FILE_NAME);
xmlFile.setFileName(xmlFileName);
if ( ! xmlFile.open(QIODevice::ReadOnly|QIODevice::Text) )
{
QMessageBox* msgBox = new QMessageBox();
msgBox->setText("File Not Found !!");
msgBox->setWindowFlags(Qt::WindowStaysOnTopHint);
msgBox->exec();
}

Try to open file with full path like:
xmlFile.setFileName(QCoreApplication::applicationDirPath() + QLatin1Char('/') + xmlFileName);

If you run your code with the run button from Qt Creator, the Content.xml needs to be in the same folder as your code is.

Related

Matlab Use Regex Expression to load file from directory

I have looked a lot for this but have not found anything. I am very new to matlab and regex in general.
My problem is, have a directory path 'dir' with only one .txt file in it. I do however not know the filename of the txt file. I want to load this file.
I have tried multiple things but cannot find the solution.
foo = load(fullfile(dir, '-regexp', '*.txt'))
Thank you for your help!
That syntax isn't valid for fullfile, and dir is an in-built function which it appears you're using as a variable... Here is something a little clearer which should work when you have a single txt file within a given folder
folder = 'my\folder\path\';
files = dir( fullfile( folder, '*.txt' ) );
if numel( files ) ~= 1
error( 'More or less than one .txt file found!' );
end
filepath = fullfile( files(1).folder, files(1).name );
foo = load( filepath ); % load is designed for .mat files, if your .txt contains anything
% non-numeric then you may want something more like readtable here...

Printing a PDF file from Qt

I have found following code snippet which works as my expectation, but the problem is that, when a PDF file is open and user print the PDF file with some other printer from the PDF reader and not close the PDF reader and again print the PDF file from my application, it will print with printer which is configured on PDF reader not the printer which I set as to print the PDF file.
Example:
On application I set Printer_1 as to print PDF file.
Print the file (it will open the file in PDF reader and print with Printer_1 printer).
On PDF reader I go to CTRL + P to print and there I select Printer_2 and click on print.
I don't close the PDF reader and again on application (printer is selected to Printer_1), I print the PDF file. Now the print command is sent to Printer_2 instead of Printer_1.
Please what is the problem in the following code snippet?
#include <QSettings>
#include <QProcess>
#include <QDebug>
int main(int argc, char *argv[])
{
const QString classesRoot = "HKEY_CLASSES_ROOT";
// get ID of .pdf extension
QSettings pdfSettings(classesRoot + "\\.pdf", QSettings::NativeFormat);
QString pdfId = pdfSettings.value("Default").toString();
// get path to default program that associated with PDF files
QString printPath = QSettings(classesRoot + "\\" + pdfId + "\\shell\\print\\command", QSettings::NativeFormat).value("Default").toString();
QString openPath = QSettings(classesRoot + "\\" + pdfId + "\\shell\\open\\command", QSettings::NativeFormat).value("Default").toString();
qDebug() << "print path" << printPath;
qDebug() << "open path" << openPath;
// open .pdf file
QProcess::startDetached(openPath.arg("full path to pdf file.pdf") );
// print .pdf file
QProcess printProcess;
printProcess.start(printPath.arg("full path to pdf file.pdf") );
printProcess.waitForFinished(-1);
return 0;
}
instead of line
QString printPath = QSettings(classesRoot + "\\" + pdfId + "\\shell\\print\\command", QSettings::NativeFormat).value("Default").toString();
use this and all works as expected:
QString printPath = QSettings(classesRoot + "\\" + pdfId + "\\shell\\printto\\command", QSettings::NativeFormat).value("Default").toString();
And pass "filename", "printer name" ,"printer driver" and "port" [driver name and port are not mandatory]
I'm sorry but I'd said that this seems reasonably to be the expected behaviour: if the application is already open and it is designed not to open separate instances for the same file (as many viewers do and as yours does), then is highly probable that current settings (in your case, the current printer) are preserved too, since, basically, nothing has changed. If you reproduce your steps but replacing your program by your own manual opening of the PDF file, I'm quite confident that you'll see the same results.
An option would be to avoid opening an external viewer and directly load the PDF file (currently using a third-party library, such as Poppler) and print it using Qt's modules. You can check this answer for more information about it.

Executing an .exe file on files in another folder

I have my python code that runs a C++ code, which takes files in another folder as input.
I have my codes in folder A, and the input files are in folder B, and I have been trying this:
path = 'C:/pathToInputFiles'
dirs = os.listdir(path)
for path in dirs:
proc = subprocess.Popen([fullPathtoCppCode, inputFiles])
However, I keep receiving WindowsError: [Error 2] The system cannot find the file specified
The only way it works is when I put the C++ executable file in the same folder of the input files, which I am avoiding to do.
How can I make python reads the file path properly?
Try using os.path.join after your for statement.
path = os.path.join(directory, filename)
for example
def test(directory):
for filename in os.listdir(directory):
filename = os.path.join(directory, filename)
proc = subprocess.Popen([fullPathtoCppcode, inputFiles])

How to read a XML file using fstream in IOS

I am using XCode, and here is a c++ code in XCode
std::fstream stream("templates.Xml", std::ios::binary | std::ios::in);
if(!stream) return false;
I put the Xml file in the folder that contain the ".xcodeproj", and I put it in the folder that contains ".app" but the stream always return false, why?
It looks like you are trying to open the file from the wrong directory.
"templates.Xml" is saved in the bundle- is not saved in the documents directory. By default, if you open "./filename", this actually points to:
/Users/arinmorf/Library/Application Support/iPhone Simulator/7.0.3/Applications/246E91F9-FAB2-4A46-B1F1-855B5363F24D/Documents/
Where arinmorf would be your username and the long hex string is randomly generated every time you install the app on the simulator.
The templates.xml file would be found in:
/Users/arinmorf/Library/Application Support/iPhone Simulator/7.0.3/Applications/246E91F9-FAB2-4A46-B1F1-855B5363F24D/iFly.app/templates.xml
iFly.app is the name of my app, yours would be "T". BUT you can't use the absolute path in your project, because of the randomly generated string, you need to use the NSBundle or CFBundleRef.
In objective-C, you would use:
filePath = [[NSBundle mainBundle] pathForResource:#"templates" ofType:#"xml"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
In C++ it looks like:
CFURLRef fileURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("templates"), CFSTR("xml"), NULL);
CFStringRef filePath = CFURLCopyFileSystemPath(fileURL, kCFURLPOSIXPathStyle);
CFStringEncoding encodingMethod = CFStringGetSystemEncoding();
const char *path = CFStringGetCStringPtr(filePath, encodingMethod);
FILE* f = fopen(path, "r");
(Credit to Chris Frederick at https://stackoverflow.com/a/8768366/2070758 for C++ version)
Yes, I solved the problem in two ways either depending on Main Bundle, or create custom bundle and use it.

QFileDialog: adding extension automatically when saving file?

When using a QFileDialog to save a file and to specify the extension (like *.pdf) and the user types in a name without this extension, also the saved file hasn't this extension.
Example-Code:
QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setNameFilter("PDF-Files (*.pdf)");
fileDialog.exec();
QFile pdfFile(fileDialog.selectedFiles().first());
now when the user enters "foo" as the name, the file will be saved as "foo", not as "foo.pdf". So the QFileDialog doesn't add the extension automatically. My question: How can I change this?
You could use QFileDialog::setDefaultSuffix():
This property holds suffix added to the filename if no other suffix was specified.
This property specifies a string that will be added to the filename if it has no suffix already. The suffix is typically used to indicate the file type (e.g. "txt" indicates a text file).
For multiple file filters, the following can be done.
import re
import os
def saveFile(self):
path, fileFilter = QFileDialog().getSaveFileName(self, "Save file",
"", "Gnuplot Files (*.plt)"
+ ";;" + "Gnuplot Files (*.gp)"
+ ";;" + "Gnuplot Files (*.gpt)"
+ ";;" + "Text Files (*.txt)")
selectedExt = re.search('\((.+?)\)',fileFilter).group(1).replace('*','')
# Attach extension as per selected filter,
# if file does not have extension.
if not os.path.splitext(path)[1]:
path = path + selectedExt
print(path)