Copying Files Using C++ on a Mac
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 apparentl开发者_如何学Cy 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.
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'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.
精彩评论