开发者

SHELL, Save echo's output in to a file (c code)?

I was trying to write a shell program(in c) and came across the following problem. Can any one please tell me how can I save the output of an echo in to a file. For example, some one m开发者_如何学JAVAight type in echo document_this > foo1 then I want to save document_this in to a file name foo1.

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

Any help would be greatly appreciated. can't use #include <fstream>, anything else I should use? Thanks.


You should separate the check for redirection from the command itself. First, loop to check for redirection:

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

Adding proper error checking is left as an exercise.


Open file named foo1 for writing, write it's contents, and close file.


You seem to be tying the output logic with the command logic, which is something that will not work so well once you have more than one command. Once you have processed the line, first write the logic of echo as in "copy its parameters to output" and then decide what to do with output (write to file or print to screen).

Of course this is a very basic approach of writing a shell.


You can't use <fstream> in a C program; it is a C++ header.

You'll need to use <stdio.h> and you'll need to use fprintf() rather than just printf(). You open a file ('foo1') and write to that instead of to standard output. So, you'll have a 'current output file', which you can direct to standard output by default, but to other files on demand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜