gpt4 book ai didi

c - SHELL,将 echo 的输出保存到文件中(c 代码)?

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:37 25 4
gpt4 key购买 nike

我试图编写一个 shell 程序(在 c 中)并遇到了以下问题。谁能告诉我如何保存 echo 的输出?到一个文件中。例如,有些人可能会输入 echo document_this > foo1然后我想保存 document_this输入文件名 foo1。

if(strcmp(myargv[0],"echo") == 0)
{
printf("Saving: %s in to a file", myargv[1]);
.
.
.
}

如有任何帮助,我们将不胜感激。无法使用 #include <fstream> ,还有什么我应该使用的吗?谢谢。

最佳答案

您应该将重定向检查与命令本身分开。首先,循环检查重定向:

FILE* output = stdin;

for (int i = 0; i < myargc - 1; ++i)
if (strcmp(myargv[i], ">") == 0)
{
output = fopen(myargv[i + 1], "w");
myargc = i; // remove '>' onwards from command...
break;
}

// now output will be either stdin or a newly opened file

// evaluate the actual command

if (strcmp(myargv[0], "echo") == 0)
for (int i = 1; i < myargc; ++i) // rest of arguments...
{
fwrite(myargv[i], strlen(myargv[i]), 1, output);

// space between arguments, newline afterwards
fputc(i < myargc - 2 ? ' ' : '\n', output);
}
else if (... next command ...)
...

// close the output file if necessary
if (output != stdin)
fclose(output);

添加适当的错误检查留作练习。

关于c - SHELL,将 echo 的输出保存到文件中(c 代码)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4394397/

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