繁体   English   中英

如何在Linux中使用c或c ++而不使用system()或exec()函数的情况下调用pwd或ls -l之类的系统函数?

[英]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 getcwdman popen将为您提供大量信息...

我正在尝试打印当前目录的路径

使用库函数getcwd()

要使用该功能,可能需要#define _XOPEN_SOURCE 500或类似名称(有关详细信息,请参见上面链接的手册页)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM