我用 C++ 为 Windows 编写了一个程序,它使用了复制终端命令。我试图将其更改为 cp,但它的工作方式与 Windows 上的复制不同。在 Windows 上,运行 shell 命令的默认目录是应用程序所在的目录。在 Mac 上,我显然需要指定完整的文件路径。我想为最终用户尽可能简化流程,因为我想要的文件应该始终与可执行文件位于同一文件夹中,所以最好是我可以简单地复制文件而不需要他们指定位置。
最佳答案
您可以使用 _NSGetExecutablePath()
获取可执行文件的位置。像这样的东西:
#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
}
您可以通过检查结果值并为 char
缓冲区使用动态大小来使其更加稳健。
为什么不使用 C/C++ 文件操作函数/类来复制文件,而是使用 system()
?它们是可移植的(即,您不必担心 Windows 与 Mac OS 与 Linux 与……),并且可以说会为您提供更好的错误检查和报告。
关于c++ - 在 Mac 上使用 C++ 复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5691097/