为什么我在Linux的C 中获得错误的当前目录
why I get the wrong current directory in C++ of linux
我使用NetBeans来编程C ,我想获得可执行文件的当前绝对路径
(~/NetBeansWorkSpace/project_1/dist/Debug/GNU-Linux-x86/executableFileName)
所以我使用
1, system("pwd")
2, getcwd(buffer,bufferSize)
然后单击"运行"按钮,但它们都遇到了错误的路径:〜/netbeansworkspace/project_1
这是惊喜,我运行了bash
cd ~/NetBeansWorkSpace/project_1/dist/Debug/GNU-Linux-x86/executableFileName
./executableFileName
我得到了正确的道路。
这是为什么???
正如其他所有人所说的那样,NetBeans在运行应用程序之前正在设置工作目录。如果您想获得可执行文件的工作目录,我相信以下内容应该有效。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const* *argv) {
char *resolved = realpath(argv[0], NULL);
if (resolved != NULL) {
char *fname = strrchr(resolved, '/');
if (fname != NULL) {
fname[1] = ' ';
}
printf("absolute path of %s is %sn", argv[0], resolved);
free(resolved);
} else {
perror("realpath");
}
return EXIT_SUCCESS;
}
没有什么错-Netbeans正在运行您的程序,而当前工作目录将设置为项目目录(~/NetBeansWorkSpace/project_1
)。
您的程序不应取决于当前目录与程序所在的目录相同。如果您想查看一些不同的方法来获取程序的绝对路径。
NetBeans通过将路径dist/Debug/GNU-Linux-x86/
的前缀启动~/NetBeansWorkSpace/project_1/
启动您的应用程序。
打开外壳,执行CD ~/NetBeansWorkSpace/project_1/
,然后做dist/Debug/GNU-Linux-x86/executableFileName
,您将获得相同的结果,就像您从NetBeans运行了应用程序。
for Linux:
函数执行系统命令
int syscommand(string aCommand, string & result) {
FILE * f;
if ( !(f = popen( aCommand.c_str(), "r" )) ) {
cout << "Can not open file" << endl;
return NEGATIVE_ANSWER;
}
const int BUFSIZE = 4096;
char buf[ BUFSIZE ];
if (fgets(buf,BUFSIZE,f)!=NULL) {
result = buf;
}
pclose( f );
return POSITIVE_ANSWER;
}
然后我们得到应用名称
string getBundleName () {
pid_t procpid = getpid();
stringstream toCom;
toCom << "cat /proc/" << procpid << "/comm";
string fRes="";
syscommand(toCom.str(),fRes);
size_t last_pos = fRes.find_last_not_of(" nrt") + 1;
if (last_pos != string::npos) {
fRes.erase(last_pos);
}
return fRes;
}
然后我们提取应用程序路径
string getBundlePath () {
pid_t procpid = getpid();
string appName = getBundleName();
stringstream command;
command << "readlink /proc/" << procpid << "/exe | sed "s/\(\/" << appName << "\)$//"";
string fRes;
syscommand(command.str(),fRes);
return fRes;
}
不要忘记在
- 为什么这不会在当前目录中生成文件?
- 下载到当前目录
- 如何使用GetPrivateProfilestring()从当前目录上升级目录
- g++ 不会先搜索当前目录中的标头
- 如何使用<windows.h获取当前目录名称> C++
- 如何使肮脏忽略当前目录
- 如何将文件写入当前目录而不是Bazel-Out
- GetPrivateprofilestring 不会获取当前目录中的 ini 文件
- 无法写入可执行对象的当前目录中的文件夹
- C - 如何获得C 可执行文件的当前目录
- 获取当前目录,我可以在不知道最大缓冲区大小的情况下进行
- 仅在当前目录中搜索标签
- c++ GetPrivateProfileString 从当前目录读取 ini 文件
- C 为什么我的代码将注册表密钥放在错误的目录中
- 为什么我在Linux的C 中获得错误的当前目录
- 正在获取当前目录中的所有文件
- 当前目录的文件路径C++
- 阻止 GCC 在包含搜索路径上搜索当前目录"-I-"选项
- 正在打印当前目录c++的内容
- 在C++中设置正在运行的应用程序的当前目录