使程序使用输入和文件
Make a program work with input and a file
我正在制作一个仅适用于键盘输入的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;
}
}
当然,您需要代码来解析命令并执行它。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 使用mongocxx驱动程序时包含头文件问题
- 使用VerQueryValue检索应用程序的文件描述
- 编译多文件C++程序
- Visual C 32位整数从文件到8位字符到文件 - 程序在某些整数上崩溃
- 文件程序不会停止显示垃圾值
- 简单的QT从文本文件程序中读取不编译
- 从文件 C++ 程序读取停止工作
- C++ - 需要有关如何正确设计多文件程序的建议
- C++文件 I/O - 程序挂起
- 简单的文件 I/O 程序C++
- 有一个简单的程序文件/程序文件(x86)指令的c++在windows
- 配置文件c++程序在perf
- 从同一文件夹读取文件(c++程序)
- 单文件程序的未定义虚函数表
- 无法用多文件程序创建SDL线程
- 我的第一个多文件C++程序不断给我错误消息
- 配置文件C++程序基于墙上的时钟时间与英特尔Vtune放大器
- c++复制文本文件程序使用头文件