I wrote a program for Windows in C++ and it utilized the copy terminal command. I tried to change it to cp, but it didn't work the same way as copy on Windows. On Windows, the default directory from which shell commands run is the one in which the application is located. On the Mac, I apparently need to specify a full file path. I want to make the process as streamlined as possible for the end-users and since the file that I want should always be in the same folder as the executable file, it would be best if I could simply duplicate the file without requiring them to specify the location.
Asked
Active
Viewed 2,361 times
3
-
Is your program an application bundle? – Apr 17 '11 at 02:57
-
No. Just a single file compiled in xCode. – Person Apr 17 '11 at 03:05
2 Answers
2
You can use _NSGetExecutablePath()
to get the location of the executable file. Something like:
#include <stdio.h>
#include <mach-o/dyld.h>
#include <libgen.h>
// use some sensible size here
#define BUFSIZE 4096
uint32_t bufsize = BUFSIZE;
char exepath[BUFSIZE];
int result = _NSGetExecutablePath(exepath, &bufsize);
if (result == 0) { // _NSGetExecutablePath() worked
char command[BUFSIZE];
char *filename = "somefile.txt";
char *destination = "/tmp/";
sprintf(command, "/bin/cp %s/%s %s", dirname(exepath), filename, destination);
result = system(command);
if (result == // error checking here
}
You can make this more robust by checking the result values and using a dynamic size for the char
buffers.
Why don’t you use C/C++ file manipulation functions/classes to copy the file instead of using system()
? They’re portable (i.e., you wouldn’t have to worry about Windows vs. Mac OS vs. Linux vs. …) and would arguably give you better error checking and reporting.
-
It was an application that I made for fun for Windows that got strangely popular, so I never originally anticipated that I would need to port it. – Person Apr 18 '11 at 17:52
-
@Person I see. Well, you’ll need to have a Mac OS-specific version because of `_NSGetExecutablePath()` anyway. The `__APPLE__` preprocessor macro is useful in case you want to use the same source file for both Windows and Mac OS X. – Apr 18 '11 at 21:31
1
It's simple and portable to copy files using boost::filesystem::copy_file. Unfortunately, your main problem boils down to getting the path of the executable, and there's no portable way to do it.