gpt4 book ai didi

命令提示符程序 : how to allow user to enter unix commands?

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:12 24 4
gpt4 key购买 nike

我在编写一个显示命令提示符(这里没问题)的 C 程序时遇到问题,该命令提示符允许用户输入 unix 命令然后显示结果。我已经尝试了很多东西,但我一年前才开始编程,除了显示命令提示符外什么也没去;我需要有关如何接受 unix 命令并显示其结果的帮助。

我唯一的限制是,我需要我的程序搜索路径环境变量中指定的目录并找到命令的可执行文件的位置,而不是用户提供绝对路径。我也不明白如何执行此操作,但在线搜索告诉我最好使用“getenv() 访问 OS PATH 变量并适本地为用户提供的命令添加前缀”。有人可以帮我从这里出去吗?提前感谢您的帮助。

最佳答案

尝试popen(),可以找到here在联机帮助页中。

检查一下:

#include <stdio.h>
#include <stdlib.h>

void write_netstat(FILE * stream)
{
FILE * outfile;
outfile = fopen("output.txt","w");
char line[128];

if(!ferror(stream))
{
while(fgets(line, sizeof(line), stream) != NULL)
{
fputs(line, outfile);
printf("%s", line);
}
fclose(outfile);
}
else
{
fprintf(stderr, "Output to stream failed.n");
exit(EXIT_FAILURE);
}
}

int main(void)
{
FILE * output;
output = popen("netstat", "r");

if(!output)
{
fprintf(stderr, "incorrect params or too many files.n");
return EXIT_FAILURE;
}

write_netstat(output);

if(pclose(output) != 0)
{
fprintf(stderr, "Could not run 'netstat' or other error.n");
}
return EXIT_SUCCESS;
}

这会将 netstat 打印到文件中。您可以对所有命令执行此操作。它使用 popen()。我写它是因为我需要一个 netstat 日志。

关于命令提示符程序 : how to allow user to enter unix commands?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com