Using Linux input redirection in a C++ code test

I’m testing a function that does a numerical calculation, namely the Cholesky matrix factorization.  I found a reference to algorithm that does this, but how do I test my code quickly, to input some data, perform the calculation, and then output some results?

It turns out Linux gives us a simple way to do this!  Using “input redirection”, we can quickly input some data from a text file, and process it as if we were inputting it directly through the keyboard.  First let’s look at some pseudocode.

#include <stdio.h>

#include <math.h>

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

ofstream out; //for debugging

double myFun (double input1, double input2) //insert the function you want to test here

int main()


//Let's say you need to enter an n by n matrix with a text file, and you know n in advance. Then:

double input[52][52]; //you can use a vector of vectors, or a 2d C-style array if needed

int i = 0; int j = 0;

for (int k = 0; k < 52*52; k++)


cin >> input[i][j];


if (j == n)


j = 0; i++;



//call myFun to test.  Then, use cout or the output stream to output your results.

//to open the output stream, simply write"myOutput.txt") and then use out << to output whatever you need.

return 0;


Now, if you have data in space or tab delimited format in a textfile, all you have to do is compile your program:

g++ myFile.cpp -o myExecutable

And then run it with input redirection:

./myExecutable < myData.txt

where the < operator feeds in the contents of myData.txt into the standard input of your program.  For more on input redirection read here, and feel free to comment!

2 thoughts on “Using Linux input redirection in a C++ code test

  1. Output redirection and piping are pretty awesome too! For example with Dave’s sensitivity analysis, you can do
    generate sequence | model evaluation | compute sensitivity > output
    all in one line.

  2. I should’ve mentioned this the first time around — but you can use this to test the input/output programs associated with “Command Line Interface” Borg or MOEAframework. The redirection is equivalent to having the algorithm generate new solutions for your program to evaluate.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s