Thursday, May 30, 2013

Redirecting files to standard input in Visual C++ 2012

Back in my university days when I use to code on Linux, I used pipping quite a bit to pass files to my programs.  What is pipping? You can think of it as redirecting the input inside a file to the standard input of your program.

Think of it as an easy way to avoid having to type stuff over and over again.  For example, you might be writing a program and you have a "fixed" input that you want to keep using as you modify and debug your program further.  If you are working from the console, you will have to type this input many times "by hand."  A better approach is to place this fixed input inside a text file and "pipe" it to your program.

One way to do this is to add the input text file in question to the directory where your executable resides and use the < character like the following:

C:\MyProject1\MyProgram.exe < input.txt

This is fine if you intend to debug by using lots of cout calls.  I tend to dislike this approach since I want to use Visual Studio and all its great debugging features.

In order to accomplish the same task and pipe the file to Visual Studio, you can redirect the file by going to  (Visual Studio 2012 Pro):

Project -> Properties -> Debugging -> Command Arguments

Add the following to your Command Arguments

< input.txt

In order for this to work without specifying the full path to your file, make sure to place the file in the same location where VS creates source files.  Now when you debug from within VS you don't have to type the input again and again!