0

I am making a shell interpreter which works only with keyboard input, but I have to make it work with a text files.

int main(int argc, char *argv[], char *envp[]) {
  string comando;
  mi_argv[0] = NULL;
  int pid_aux;    
  el_prompt = "$> ";

  if(argv[1] != NULL)
  {
    ifstream input(argv[1]);
    if (!input)
    {
        cerr << "No se reconoce el archivo " << argv[1] << endl;
        exit(EXIT_FAILURE);
    }
  }

  while(!cin.eof())
  {
     cout << el_prompt;
     getline(cin, comando);
  ...
  }
} 

The point is to make this work with a file like argument ./shell file.txt. I tried to redirect the file to cin, but I don't know how to do it.

Mat
  • 202,337
  • 40
  • 393
  • 406
mbayon
  • 103
  • 4
  • possible duplicate of [How to redirect cin and cout to files?](http://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files) – Serge Ballesta May 17 '15 at 09:59

2 Answers2

1

Put the code reading from the input stream in a separate function, and pass a reference to the input stream to the function. Then you can pass any input stream to the function, a file you have opened or std::cin.

Like e.g.

void main_loop(std::istream& input)
{
    // Use `input` here like any other input stream
}

Now you can call the function either with standard input

main_loop(std::cin);

or your file

main_loop(input);

Also, be careful with that loop condition, doing while (!stream.eof()) will in most cases not work as expected. The reason being that the eofbit flag is not set until after you try to read from beyond the end of the stream, and will lead to the loop being run one extra time.

Instead do e.g. while (std::getline(...)).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Work perfect with keyboard input, but when i use a file, print all the commands and then print the prompts, maybe a thread problem. I remove the prompt when there is a file, but if you have a better solution i'll appreciate it. Thanks so much!. – mbayon May 17 '15 at 11:52
0

Something like this.

#include <string>
#include <iostream>
#include <fstream>


void usage() {
    std::cout << "Usage: shell <filename>\n";
}

int main(int argc, char* argv[]) {
    std::string comando;
    std::string el_prompt = "$> ";

    if (argc != 2) {
        usage();
        exit(1);
    }

    std::ifstream input(argv[1]);
    while (std::getline(input, comando)) {
        std::cout << el_prompt << comando;
    }
}

You would need code of course to parse the command and execute it.

Angus Comber
  • 9,316
  • 14
  • 59
  • 107