linux - C++: how to get input using two kind of ways,like cin and file? -


i have written c++ program can info file, must support 2 ways of reading data.

the first way passing filename command line parameter: ./a.out a.txt

the second 1 reading pipe: cat a.txt | ./a.out

the second way more important , more difficult me. how can done?

here detail question:

there class,which defined this:

class api_export samreader{

// constructor / destructor 

public: samreader(void); ~samreader(void);

// closes current sam file bool close(void); // returns filename of current sam file const std::string getfilename(void) const;  // return if sam file open reading bool isopen(void) const;  // opens sam file // *** here is question bool open(const std::string& filename); bool open(std::istream cin); //here~~~~  // retrives next available alignment bool loadnextalignment(bamalignment& alignment); 

private: internal::samreaderprivate * d; };

i have got way input file , result, need add func in class, make can input stdin...

thanks help, new guy here , appreciate people me now.

to read pipe, program need read stdin. that's how pipe in shell works, if run a | b, passes output on stdout of a stdin of b.

so program needs cover 2 cases: (1) read file if 1 provided , (2) read stdin otherwise.

to avoid code repetition, easiest way read stdin. cover (2). cover (1), when file provided param, use freopen override stdin file.

#include <fstream> #include <iostream> #include <string>  using namespace std;  int main(int argc, char** argv) {   if (argc > 1) {     freopen(argv[1], "r", stdin);   }    string s;   while (cin >> s) {     cout << s << endl;   }    return 0; } 

demonstrating how works

$ g++ test.cc $ cat content test $ ./a.out content test $ cat content | ./a.out test 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -