使用 stdio 重定向 Unix 和C++上的输入和输出文件

Redirecting input and output files on Unix and C++ using stdio

本文关键字:输入 输出 文件 C++ stdio 重定向 Unix 使用      更新时间:2023-10-16

我需要这样做:

$ ./compiledprog.x < inputValues > outputFile

这样我就可以从文件中读取inputValues对于我们的情况,这些文件可能只是n int值或其他值分开。 然后printf()任何事情都会进入outputFile. 但是从技术上讲,这叫什么,我在哪里可以找到这样做的演示。

正如其他人所指出的,它是输入/输出重定向。

下面是一个示例程序,它将标准输入复制到标准输出,在您的示例中,将内容从 inputValues 复制到 outputFile。在程序中实现您想要的任何逻辑。

#include <unistd.h>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
#include <string>
using std::string;
int main(int argc, char** argv) {
        string str;
        // If cin is a terminal, print program usage
        if (isatty(fileno(stdin))) {
                cerr << "Usage: " << argv[0] << " < inputValues > outputFile" << endl;
                return 1;
        }
        while( getline(cin, str) ) // As noted by Seth Carnegie, could also use cin >> str;
                cout << str << endl;
        return 0;
}

注意:这是快速而脏的代码,需要行为良好的文件作为输入。可以添加更详细的错误检查。

称为 I/O 重定向。