Tuesday 1 October 2013

Output Redirection: Send Your Results To A Text File

In the last post, we redirected input to come from a text file as opposed to coming from the keyboard. Using the text file from the last post, the output was:

Enter the numbers (any alphabet to calculate total): 
The total is 55

How about if we wanted to send the result (Output) to a text file?
Just like we discussed in the last post, The program (mine is named 'test.exe') and the text file ('AddThese.txt') are both in the same folder. To send the output to a text file, we will use the '>' redirection operator.

The command entered would be this:

test <addthese.txt >output.txt


Below is a breakdown of the above command:


test          : (This is the name of the program you wrote)
<addthese.txt : ( insert the data in addthese.txt into the program test.exe when it runs)
>output.txt   : (extract the output from the program test.exe to the text file output.txt)


After entering the command, you will have to press any key once (because of the getch() at the end of the program)
That should create a file called 'output.txt' in the same folder. If you open it in notepad, it will contain the text:

Enter the numbers (any alphabet to calculate total): 
The total is 55

Alright. That's all good. But I'd rather not have the "Enter the numbers (any alphabet to calculate total):" in the output file. We cold easily remove "printf("Enter the numbers (any alphabet to calculate total): \n");"  from the program itself, but then, if this were a useful program, this prompt will be expected by a user when trying to add numbers from the keyboard. If the user is not using redirection, they would be greeted by nothing but a blinking cursor.

Print the prompt as an error message, nobody but the computer and us would know it's being printed as an error. Also during redirection, the "error" message would be sent to the screen and not a file.

When I type 
printf("Enter the numbers (any alphabet to calculate total): \n");
in a program, it the same as typing:
fprintf(stdout,"Enter the numbers (any alphabet to calculate total): \n");

'stdout' means standard output. Change that to 'stderr' (standard error) and we have our program.

#include <stdio.h>
#include <conio.h>

int main()
{
    int x,y=0;

    fprintf(stderr,"Enter the numbers (any alphabet to calculate total): \n");

    //the next line will run as long as scanf is able to read one input
    while(scanf("%i,",&x)==1)
    {
        y=y+x;
    }
    printf("The total is %i",y);
    getch();
    return 0;

}


Redirection still shows the prompt, gets the input from 'AddThese.txt', adds them, sends it to file, waits for keypress, then ends.
I typed the output file (it can be opened in notepad too) and it contains the total. There we go......


Finally, what if I wanted to send the ERROR to file but not the output?

Command is:
test <addthese.txt 2>output.txt

No comments:

Post a Comment