我有一个简单的程序,它在执行时创建一个目录:
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(){
if(int a = mkdir("abc",0700)){
std::cout << "Failed to create: " << a << std::endl;
}
else{
std::cout << "Created." << std::endl;
}
}
对于两种不同的用例,它的行为有所不同:
Created.
Failed to create: -1
如何通过Finder启动此程序以创建文件夹abc
而不使用Cocoa框架(仅使用g ++编译)?
答案 0 :(得分:0)
感谢Wooble
在评论部分指出问题是由工作目录引起的。当我通过Finder启动它时,当前的工作目录是我的主目录。
以下是我解决问题的方法:
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libproc.h>
int main(int argc, char** argv){
// Gets and prints out the current directory
char cwd[1024];
getcwd(cwd, sizeof(cwd));
std::cout << "Current Working Directory: " << cwd << std::endl;
// Above is not necessary
// Changes working directory to directory that contains executable
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
if(proc_pidpath (getpid(), pathbuf, sizeof(pathbuf)) > 0){ // Gets the executable path
std::string s(pathbuf);
s = s.substr(0,s.find_last_of('/')); // Removes executable name from path
std::cout << "Executable Path: " << s << std::endl;
chdir(s.c_str()); // Changes working directory
}
if(int a = mkdir("abc",0700)){
std::cout << "Failed to create: " << a << std::endl;
}
else{
std::cout << "Created." << std::endl;
}
}