Parsing terminal arguments Qt Mac OS X - c++

I have a simple text editor in which I would like to open a file when it's double-clicked from the system file manager.
I managed to do that without any problems under Ubuntu Linux (13.04), but in Mac OS X my code did not work.
After researching a bit, I found out that you need to add the --args argument in terminal in order to parse the arguments to main().
I fixed my code and now my application bundle can open files from the terminal, but when I double click a file in Finder (and select my app), my application launches as if did not receive any terminal arguments (creates a new file).
Here is the code of the main() function:
int main(int argc, char *argv[])
{
QApplication MyApp(argc, argv);
Textpad.setApplicationName("MyApp");
Textpad.setApplicationVersion("0.7.2");
Textpad.setWindowIcon(QIcon(":/app-icon/48x48/icon.png"));
MainWindow *Window = new MainWindow();
QString Arguments;
QString FileLocation;
if (argc != 1) {
int i;
for (i = 0; i < argc; i++)
Arguments = argv[i];
// Check if the OS is Mac OS X (Mac OS X is 3)
if (Window->CheckOS() == 3)
// Remove the "--args" so that we don't confuse it with the file location
Arguments.replace("--args", "");
if (Arguments == "--help") {
// Show help
}
// Create a new file when Textpad is launched normally (under Linux)
if (Arguments == "%U") {
FileLocation.clear();
// Load settings and create UI
Window->Initialize();
// Open the requested file
Window->LoadFile(FileLocation);
}
else {
FileLocation = Arguments;
// Load settings and create UI
Window->Initialize();
// Open the requested file
Window->LoadFile(FileLocation);
}
}
else {
// Create new file
FileLocation.clear();
// Load settings and create UI
Window->Initialize();
// Open the requested file
Window->LoadFile(FileLocation);
}
return MyApp.exec();
}
As I said before my application opens files without probles from the terminal when I write the following:
open MyApp.app --args <location of my file>
But fails when I try to open a file from Finder.
What I am missing?
Thank you in advance.

First of all, you will have to link against the OX-X Framework. OSX works with Events similar to signal slots. The filename will also be given by an apple event. I`ve had this quite some time ago with another language, but i still found a reference:
Edit doc now in Qt archive:
https://doc.qt.io/archives/qq/qq12-mac-events.html

Related

C++ ifstream fails to read on BSD Machine

I have a problem with reading lines from a .txt file in C++.
The code is compiled with gmake on a FreeBSD environment.
So here is my code
int main(int argc, char **argv)
{
std::string temp_value_line;
std::string filename = "values.txt";
std::ifstream open_file(filename.c_str());
if (!open_file.is_open()) {
sys_err("Failed to load values from values.txt");
return 0;
}
int counter = 0;
while (!open_file.eof())
{
open_file >> temp_value_line;
str_to_number(common_value[counter], temp_value_line.c_str());
counter++;
}
sys_log(0, "values loaded succsefully");
open_file.close();
}
After building and running the application, there is the specified error message in my error log, so the file is not opened.
I already checked if there is a permissions or naming problem like "values.txt.txt" but everything seems to be okay. I am able to read/modify the file via console editor.
Thanks in advance.

How to specify command line arguments for my C program when running it from the Eclipse IDE

I have some code that is executed from the command line. It takes 3 parameters:
"example.txt" 3 s
I want to be able to run this program from inside of my Eclipse IDE instead of running it from the command line but I do not know how to assign the parameters without creating bugs int the program.
Here is the main method below:
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <input file> <num clusters> "
"<linkage type>\n", argv[0]);
exit(1);
} else {
item_t *items = NULL;
int num_items = process_input(&items, argv[1]);
set_linkage(argv[3][0]);
if (num_items) {
cluster_t *cluster = agglomerate(num_items, items);
free(items);
if (cluster) {
fprintf(stdout, "CLUSTER HIERARCHY\n"
"--------------------\n");
print_cluster(cluster);
int k = atoi(argv[2]);
fprintf(stdout, "\n\n%d CLUSTERS\n"
"--------------------\n", k);
get_k_clusters(cluster, k);
free_cluster(cluster);
}
}
}
return 0;
}
I am using c++ and eclipse IDE.
You basically need to create a debug/run configuration for said project. Go to Run->Debug Configurations, select C/C++ Application, then create a new configuration. After that, you have to specify some information, like the application, the eclipse project, and your program`s arguments, on the Arguments Tab.
Screenshots from here are a bit old, but should give you the idea.
After that, hit Debug or Run, and Eclipse shoud start your program with the given parameters.

cstdio fopen and fclose not working correctly on osx

I'm using tinyxml through openframeworks which uses cstdio for file access. I can see the example program quite happily create and write files but there is no delete so my plan is to implement remove, but after trying to run this code in my own project it doesn't seem to create a file or notify me of an error.
This code runs as expected on windows, just not on mac osx 10.8.5, no file is generated.
#include <cstdio>
int main(int argc, const char * argv[])
{
bool bClosed = false;
bool bWritten = false;
FILE* testFile;
testFile = fopen(".\\test.xml", "w");
if(testFile)
{
bWritten = fputs("test writing.", testFile);
bClosed = !fclose(testFile);
}
return 0;
}
edit: i now know the file exists as can read from it, i just cant view it in finder, i have hidden files shown, its not found its way into the app's package contents.
On a unix-like system (e.g. Mac OS X and Linux) a Windows path as
".\\test.xml"
should rather be
"./test.xml"
Anyway the simplest solution for this case might just be
"test.xml"

stat() doesn't find a file in c++

on Linux 12.04
I have an executable file located in say:
/a/b/exe
and a config file on
/a/b/config
when doing:
cd /a/b/
./exe
everything's ok and the stat function finds the file config on /a/b/
HOWEVER,when running from root
/a/b/exe
the stat doesn't find the config file
any idea why?
it makes it impossible to run the binary using a script that isn't ran from the folder of the exe.
Edit
The call looks like this:
struct stat stFileInfo;
bool blnReturn;
int intStat;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(),&stFileInfo);
if(intStat == 0) {
// We were able to get the file attributes
// so the file obviously exists.
blnReturn = true;
} else {
// We were not able to get the file attributes.
// This may mean that we don't have permission to
// access the folder which contains this file. If you
// need to do that level of checking, lookup the
// return values of stat which will give you
// more details on why stat failed.
blnReturn = false;
}
In first case cd ..., run exe you change current working directory before executing the program, in second case you launch exe without changing current working directory, and I think in your program you use a relative path to open your config(for example ./config or just config) and it can't find it from current working directory. easiest workaround is to change working directory at start of your app:
int main(int argc, char** argv) {
std::string s( argv[0] ); // path to the program
std::string::size_type n = s.rfind( '/' );
if( n != std::string::npos ) {
std::system( ("cd " + s.substr(0, n)).c_str() );
}
// rest of your code
}

Newbie problem with QT C++ - Qimage dont work?

I am trying to do console application to read pixels from image:
#include <QtCore/QCoreApplication>
#include <QtGui/QImage>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QImage *img = new QImage("adadad.jpg");
//std::cout << "Type filename:" << std::endl;
img->isNull();
return a.exec();
}
That doesn't work I got: (IT doesn't compile, but anyway file isn't exist yet...)
File not found: tmp/obj/debug_shared/main.o:: In function `main':
What is going on? Is it impossible to use Qimage with console app?!
EDIT:
screen
It is possible to use QImage in a console application, you must make sure that QtGui is configured though. If you chose a console app, your .pro file might contain something like
CONFIG += console
QT -= gui
If that's the case, remove the QT -= gui line.
QImage("adadad.jpg");
Will probably look for a file called adadad.jpg on the current working directory for your application. Check if that file is present. Otherwise, use a fully qualified path.
img->isNull() doesn't do anything on it's own, try this instead:
if(img->isNull())
std::cout << "Image isNull!\n";
else
std::cout << "Image loaded\n";
My guess is that the local directory of the executable is not the same as the location of that image, so Qt can't find the file. Try specifying the complete path.
EDIT: Ahh... didn't realize it was a compilation problem. That looks suspiciously like a moc issue. What build system are you using? and can you confirm that the moc step is executing?
This modification of your code will compile and run as expected if there is a valid image file in the current working directory when you run the app. It will display Image loaded
#include <QtGui/QImage>
#include <iostream>
int main(int argc, char *argv[])
{
QImage *img = new QImage("adadad.jpg");
if(img->isNull())
std::cout << "Image is null";
else
std::cout << "Image loaded";
return 0;
}
You do not need to create an instance of QCoreApplication unless you have subclassed it and put your program code in that subclass.
Update:
Your program does not exit so you are probably getting that compile error because it can't replace the executable because it is still running (and locked). The file locking is more likely to be an issue under Windows.
An important note when you are loading a file using directly "adadad.jpg" in your code. Even if you put the file inside the debug/release folder, QImage will always be null if loaded this way.
I run into this problem yesterday and I fixed it by using the Qt library to get the full path: QCoreApplication::applicationDirPath().
There is two way to achieve that, first one is when you create the img object.
QImage img( QCoreApplication::applicationDirPath() + "adadad.jpg");
if( img.isNull())
{
qDebug() << "Loading Error - file: adadad.jpg.";
return false;
}
or using the load function
QImage img;
if( !img.load(QCoreApplication::applicationDirPath() + "adadad.jpg"))
{
qDebug() << "Loading Error - file: adadad.jpg.";
return false;
}