将文本文件传递给标准输入

Passing text file to standard input

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

下面的代码是一个更大的翻译器程序的一部分。下面的代码要求用户键入一行,而不仅仅是将其写回。有没有一种方法,我可以在标准输入中输入一个完整的文件等"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