简体   繁体   中英

Piping filename from standard input in linux into c++

I want to be able to write a line in a terminal (as below) that takes a text file in the same directory and inputs its name into an executable file.

cat fileName | executable

I want to be able to read the fileName into c++ code. I already have a code that accesses the lines and reads through the file, it is just receiving fileName from the standard input.

Is there a line of code or a function to read the fileName into a c++ program and store it as a string? I am currently using the below code to read through each line of the text file.

ifstream myfile; 
myfile.open(fileName.c_str());

if( myfile.is_open() )
{   
    while ( getline (myfile ,line) )
    {
                  ......
    }
}

When you do cat filename | executable cat filename | executable you are not sending the name of the file to your executable, but its contents. If you wish to send the name, use echo filename | executable echo filename | executable or executable filename . Then you can process argc and argv as usual, and do the normal file reading you are showing in your example code.

All you need to do is read from stdin into a variable (eg "fname"):

int main () {
  string fname;
  cin >> fname
  ifstream myfile;
  myfile.open (fname);
  if (myfile.is_open() ) {   
    while ( getline (myfile, line) ) {
      ...

To accomodate either "pipe the name" or "use argc/argv" (as many *nix commands do):

int main (int argc, char *argv[]) {
  string fname;
  if (argc == 1) {
    cin >> fname
  }
  else {
    fname = argv[1];
  }
  ifstream myfile;
  myfile.open (fname);
  if (myfile.is_open() ) {   
    while ( getline (myfile, line) ) {
      ...

You're actually unclear, if you want to read the file from std::cin as it would be supplied by

cat filename | executable

or if you actually get the filename to be opened passed from std::cin .

Most likely you want to have an optional command line parameter (passed to int main(int argc, char* argv[]) ), and have your reading code rely to a std::istream input source, rather than std::cin or std::ifstream hardcoded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM