c++ - 有条件地从标准输入或文件中读取文件

标签 c++

这里是新手 C++ 程序员。我正在尝试编写一个命令行应用程序,它接受两个参数,一个输入文件和一个输出文件。但是,如果输入文件或输出文件名是“-”,我需要程序改为读取/输出到标准输入/输出。我的问题是,在 C++ 中,如果编译器不知道输入/输出流已初始化,我不知道如何执行此操作。这是我的代码。

if(argv[1] == "-") {
  istream input;
  cout << "Using standard input" << endl;
}
else {
  ifstream input;
  cout << "Using input file " << argv[1] << endl;
  input.open(argv[1], ios::in);
  if(!input) {
    cerr << "Cannot open input file '" << argv[1]
    << "', it either does not exist or is not readable." << endl;
    return 0;
  }
}

if(argv[2] == "-") {
  ostream output;
  cout << "Using standard output" << endl;
}
else {
  ofstream output;
  cout << "Using output file " << argv[2] << endl;
  output.open(argv[2], ios::out);

  if(!output) {
    cerr << "Cannot open output file '" << argv[2] << "' for writing."
    << " Is it read only?" << endl;
    return 0;
  }
}

从这里我不能在输入上调用运算符 >>,因为我猜,编译器不知道它已被初始化。

最佳答案

您可以使用流的引用,然后将其初始化为引用文件流或标准输入或输出。不过,初始化必须在单个命令中进行,因此即使您不使用文件流,也必须声明它们。

ifstream file_input;
istream& input = (strcmp(argv[1], "-") == 0) ? cin : file_input;

ofstream file_output;
ostream& output = (strcmp(argv[2], "-") == 0) ? cout : file_output;

注意 &input 的声明中和 output .它们表明我们没有声明一个单独的流对象,而只是声明一个对其他流对象的引用,我们根据 argv[x] 的值有条件地选择它。 .

然后您可以根据需要打开文件。缺点是我们需要为每个输入或输出检查两次而不是一次检查“-”字符串。

if (strcmp(argv[1], "-") == 0) {
  cout << "Using standard input" << endl;
} else {
  cout << "Using input file " << argv[1] << endl;
  file_input.open(argv[1]);
  if (!file_input) {
    cerr << "Cannot open input file '" << argv[1]
         << "', it either does not exist or is not readable." << endl;
    return 1;
  }
}

此后,您可以从 input 读取并写信给output , 并且将使用文件或标准 I/O 流。


请注意我对您的代码所做的其他更改。首先,我调用 strcmp而不是使用 ==运算符(operator);运算符在比较 char* 时并没有按照您的想法去做用文字。接下来,当打开文件失败时,我返回 1 而不是 0。零表示程序成功,而非零则告诉操作系统程序失败。

关于c++ - 有条件地从标准输入或文件中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250996/

相关文章:

c++ - 使用模板和偏特化生成类型转换函数

c++ - 我可以使用 Eigen 求解线性方程组,形式为 Ax = b,A 是稀疏的吗?

c++ - 我应该使用 main.cpp 中的哪个#includes(LNK2005 已经定义)

c++ - XCode 助理编辑器不显示我的 .h 和相关的 .cpp 文件

c++ - 为什么不在范围内声明 Brake 和 Accelerate?

c++ - BST不断出现段错误

C++ 指向 vector 行为的指针

c++ - C++ 中接受 2D 数组、将其乘以整数并返回新的 2D 数组的函数?

c++ - 从函数 : by value VS by pointer 返回大对象

c++ - 在线程 A 中创建对象,在线程 B 中使用。需要互斥锁吗?