![](/img/trans.png)
[英]How to shutdown Linux using C++ or Qt without call to “system()”?
[英]how we can call a system function like pwd or ls -l without using system() or exec() function using c or c++ in linux?
我正在尝试使用此execl ("/bin/pwd", "pwd", NULL);
打印当前目录的路径execl ("/bin/pwd", "pwd", NULL);
输出: / home / user / Ubuntu并希望在当前路径之前打印所需的文本。 例如:我的名字/ home / user / ubntu
这将如何完成?
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
using namespace std;
int main(){
string command;
while(command != "exit"){
cout<< "B-17235"<<return execl ("/bin/pwd", "pwd", NULL);
cin>> command;
}
return 0;
}
认为大多数Unix-Linux-Gnu命令都是用C或C ++编写的。 通常,有直接的API调用,可以是系统调用(man 2)或标准C库(man 3)来获取信息或完成任务。
要获得工作目录,只需按照alk的建议使用getcwd()
。
char buffer[256];
if (NULL == getcwd(buffer, sizeof(buffer))) {
perror("can't get current dir");
return 1;
}
如果您想获得更复杂的命令的输出,最直接的方法是使用popen
来封装fork,exec和管道管理:
FILE *fd = popen("/bin/pwd", "r");
char buffer[256];
if (fgets(buffer, sizeof(buffer), fd) == NULL) {
perror("can't read command");
return 1;
}
if (buffer[strlen(buffer) - 1] != '\n') {
fprintf(stderr, "path too long";
return 1;
}
pclose(fd);
// ok the working directory is is buffer
你不应该使用,对作为PWD简单的命令。
而且不要忘记: man
是你的朋友! man getcwd
和man popen
将为您提供大量信息...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.