将文本文件传递给标准输入
Passing text file to standard input
下面的代码是一个更大的翻译器程序的一部分。下面的代码要求用户键入一行,而不仅仅是将其写回。有没有一种方法,我可以在标准输入中输入一个完整的文件等"translate.txt",而不是每次只写一行,程序可以逐行写回它,并在到达行尾时产生错误?
#include <iostream>
#include <string.h>
#include<stdio.h>
#include<fstream>
using namespace std;
using namespace std;
void PL() {
char line[BUFSIZ];
while( cin.good() ) {
cout<<"Type line now"<<endl;
cout<<"n";
cin.getline(line, sizeof(line));
cout<<"n"<<endl;
string mystring = string(line);
// supposed to Parsing string into words and translate//
//but just reading back input for now//
cout<<"You typed:"<<mystring<<endl;
cout<<"n"<<endl;
}
}
int main() {
PL();
}
您希望有一种方法将文件传递给您的程序吗?
executable < file
这段代码对我来说很好:
void PL() {
string line;
while(cin) {
cout<<"Type line now";
if(std::getline(cin,line)) {
// supposed to Parsing string into words and translate//
//but just reading back input for now//
cout<<"You typed:"<<line<<endl;
}
}
}
注意,那里的stdin
实际上是从shell传递到程序的,如前所述:
$ executable < file
如果你想传递从这个函数外部创建的任意类型的流,你需要像这样的东西
void PL(std::istream& is) {
string line;
while(is) {
cout<<"Type line now";
if(std::getline(is,line)) {
// supposed to Parsing string into words and translate//
//but just reading back input for now//
cout<<"You typed:"<<line<<endl;
}
}
}
int main() {
std::ifstream is("mytext.txt"); // hardcoded filename
PL(is);
return 0;
}
或者
int main(int argc, char* argv[]) {
std::istream* input = &std::cin; // input is stdin by default
if(argc > 1) {
// A file name was give as argument,
// choose the file to read from
input = new std::ifstream(argv[1]);
}
PL(*input);
if(argc > 1) {
// Clean up the allocated input instance
delete input;
}
return 0;
}
当然还有更优雅的解决方案
并从命令行调用:
$ executable mytext.txt
您的shell将有一种通过stdin传入文件的方法。例如,如果你在一个兼容bourne的shell上,你可以运行
translate < translate.txt
(假设您的程序已编译为名为translate
的二进制文件)。这是假设您希望以交互方式启动程序,即从shell启动程序。
如果你想从你编写的另一个程序中自动生成这个程序,这取决于你的操作系统。例如,在POSIX操作系统上,在分叉之后但在调用exec
族函数之前,您将希望将文件open
和生成的文件描述符dup2
STDIN_FILENO
。
相关文章:
- 从标准输入读取文件后读取用户输入
- 如何从标准输入中检测格式化输入错误?
- C++ - 标准输入环路
- 快速读取标准输入缓冲区,无需检查
- 将标准输入中的双精度存储在矢量中
- 如何将 getline 与标准输入一起使用?
- 从 C++ 中的标准输入迭代读取字节
- C++计算标准输入的字数
- 如何从 c++ 中的给定标准输入中获取每个字符的偏移量?
- 如何使输入文本文件成为构造函数参数?c++
- 用C++计算输入文本的新行数
- 为什么此代码从标准输入中少一个输入?
- 如何在C++中从标准输入中获取变量输入
- C++ 从标准输入读取文件名
- 从标准输入读取多个类型时出现问题
- 如何在execl中使用标准输入'<'?
- 如何在 eclipse 中将标准输入从控制台更改为另一个程序
- 流对象来表示文件输入,然后是标准输入?
- 查找字符在标准输入文本中出现的次数
- 将文本文件传递给标准输入