开发者

c++ read from file redirection and also keyboard

开发者 https://www.devze.com 2022-12-13 02:19 出处:网络
My program reads a list of integers from user input [ keyboard] and calculates some statistics The user enters \'x\' to terminate the input process.

My program reads a list of integers from user input [ keyboard] and calculates some statistics

The user enters 'x' to terminate the input process.

So for example,

Enter integers separated by space ( enter x to quit) : 1 2 3 4 5 x

But now I want to include the inputs to be read from file redirection also. So if the numbers followed by x is in a data file, the program shou开发者_Go百科ld take it from there if not then prompt the user


use isatty for your file descriptor (0 for standard input)

example:

#include <unistd.h>
main(){
  if(isatty(0))
    puts("tty");  // print some prompt
  else
    puts("pipe"); // not really needed in your case
}


You can read strings from a file with fstream and iostream.

Then from there you just parse the strings to see if they contain the correct data. If not, prompt the user for input?


If what you mean is that you can either call your program with a file as a command line argument, or not, in which case you want it to read from standard input, you can do something like this:

#include <fstream>
#include <iostream>

void run(std::istream& in) {
   // read all input from 'in' and run your program as normal
}

int main(int argc, char **argv) {
   if(argc == 1) {
      run(std::cin);
   } else if(argc == 2) {
      std::ifstream fin(argv[1]);
      run(fin);
   }

   return 0;
}

This way, if you call

./prog

it'll read from standard input (i.e., the keyboard), and if you call

./prog foo.txt

it'll read from the file foo.txt.

You may want to do a little more work when checking the command line arguments, but this is the basic idea.


one approach that would not require any program alterations is to let the shell do the redirection for you.

On both Windows and Unix shells, < redirects a file to stdin for the program.

So, on unix/linux/mac on a console:

./app < file.txt

or windows, at the command prompt, just:

app < file.txt

will take the contents of file.txt and send it as stdin to the program called 'app'.


On a unix box the following should work:

progream <file

where program is your program and file contain the input that the user would type in.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号