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

问题描述:

我试图编写一个shell程序(在c中),并遇到以下问题。任何人都可以告诉我如何将echo的输出保存到文件中。例如,有人可能输入echo document_this > foo1,那么我想将document_this保存到文件名foo1中。SHELL,将echo的输出保存到文件(c代码)中?

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); 

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

+0

非常感谢你的好解释。但是fputc(..)函数似乎不起作用。它说:“错误:函数的参数太少'fputc' – 2010-12-09 03:47:46

打开文件名为foo1用于写入,写入它的内容并关闭文件。

+1

由于您不想考虑的原因,shell的实际工作方式要复杂得多。这是实现你想要的简单路径。 – Joshua 2010-12-09 03:01:57

您似乎将输出逻辑与命令逻辑绑定在一起,一旦有多个命令,这种功能将无法正常工作。一旦处理完该行后,首先将回显的逻辑写为“将其参数复制到output”,然后决定如何处理output(写入文件或打印到屏幕)。

当然这是编写shell的一个非常基本的方法。

在C程序中不能使用<fstream>;它是一个C++头文件。

您需要使用<stdio.h>,您需要使用fprintf()而不是printf()。您打开一个文件('foo1')并写入该文件而不是标准输出。因此,您将拥有一个“当前输出文件”,您可以默认将其指向标准输出,但可以根据需要指向其他文件。