user3703308
user3703308

Reputation: 21

How to write console output to a text file

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

Upvotes: 2

Views: 16797

Answers (2)

Utkal Sinha
Utkal Sinha

Reputation: 1041

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

Upvotes: 9

slushy
slushy

Reputation: 3377

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

Upvotes: 3

Related Questions