How to write console output to a text file

user3703308 picture user3703308 · Jun 3, 2014 · Viewed 13.3k times · Source

I have this key generating algorithm made in C that will display all generated keys in console:

So how can I save all the keys written to console to a text file?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

static const char alphabet[] = "abcdefghijklmnopqrs";               
static const int alphabet_size = sizeof(alphabet) - 1;

void brute_impl(char * str, int index, int max_depth)
{
    int i;
    for (i = 0; i < alphabet_size; ++i)
    {
        str[index] = alphabet[i];

        if (index == max_depth - 1)
        {   
            printf("%s\n", str); // put check() here instead                     
        }
        else
        {
            brute_impl(str, index + 1, max_depth);
        }
    }
}

void brute_sequential(int max_len)
{
    char * buf = malloc(max_len + 1);
    int i;

    for (i = 8; i <= max_len; ++i)
    {
    memset(buf, 0, max_len + 1);
    brute_impl(buf, 0, i);
    }
    free(buf);
}

int main(void)
{
    brute_sequential(8);
    return 0;
}

Answer

Utkal Sinha picture Utkal Sinha · Jun 4, 2014

Professional way:

Use the below code at the beginning of your code

freopen("output.txt","w",stdout);

Another intuitive way:

In windows, once you compile your C code it will generate an .exe file (say it is dummy.exe).

Now to save the out put produced by this exe file to an external txt file (say it is out.txt), all you need to do is to browse to that exe file through CMD and type

dummy.exe > out.txt

and if you have any input to check then use

dummy.exe <input.txt> out.txt