mbayon
mbayon

Reputation: 103

Make a program work with input and a file

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.

Upvotes: 0

Views: 55

Answers (2)

Angus Comber
Angus Comber

Reputation: 9708

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.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

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(...)).

Upvotes: 1

Related Questions