使程序使用输入和文件

Make a program work with input and a file

本文关键字:文件 程序 输入      更新时间:2023-10-16

我正在制作一个仅适用于键盘输入的shell解释器,但我必须使其适用于文本文件。

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

关键是要使它与类似参数./shell file.txt的文件一起工作。我试图将文件重定向到cin,但我不知道该怎么做。

将从输入流读取的代码放在单独的函数中,并将对输入流的引用传递给函数。然后,您可以将任何输入流传递给函数,您已打开的文件或std::cin

比如

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

现在,您可以使用标准输入调用该函数

main_loop(std::cin);

或您的文件

main_loop(input);

此外,请注意该循环条件,在大多数情况下,执行while (!stream.eof())操作将无法按预期工作。原因是eofbit标志在您尝试从流的末尾读取之前不会设置,并且将导致循环额外运行一次。

相反,例如while (std::getline(...)).

像这样的东西。

#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;
}
}

当然,您需要代码来解析命令并执行它。