How to write console output to a text file

16.6k Views Asked by At

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;
}
2

There are 2 best solutions below

0
On

You can use redirection (windows) and (*nix) to send console output from any program in any language to a text file:

# to overwrite an existing file:
./my_program.a > my_outfile.txt

# or to append
./my_program.a >> my_outfile.txt
0
On

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