将c控制台输出打印到txt文件

时间:2021-03-24 07:34:39

标签: c console

我需要一些有关此 C 代码的帮助。我对 C 一无所知,我刚开始学习 C++,这绝对不是我的代码,我从 stackoverflow 获得了所有代码。无论如何,该程序运行良好,但有一些错误,程序运行流畅并提供所需的控制台输出。但我不希望它打印到控制台我希望它将所有控制台输出写入 .txt 文件。我没有 C 代码的经验,所以你能帮我。这是代码

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

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int l, int r)
{
   int i;
   if (l != r)
   {
       for (i = l; i <= r; i++)
           {
              swap((a+l), (a+i));
              permute(a, l+1, r);
              swap((a+l), (a+i)); //backtrack
           }
   }
   else
   {
       fp = fopen ("C:\Users\vidit\\Documents\\CODE\\CODE\\C++\\wrds.txt","w");
       fprintf(fp, "%s\n", a);
   }
}

/* arr[]  ---> Input Array
   data[] ---> Temporary array to store current combination
   start & end ---> Staring and Ending indexes in arr[]
   index  ---> Current index in data[]
   r ---> Size of a combination to be printed */
void combinationUtil(char alphas[], char data[], int start, int end,
                     int index, int count)
{
    int i;
    if (index == count)
    {
        data[count] = '\0';
        permute(data, 0, count-1);
        return;
    }

    for (i=start; i<=end && end-i+1 >= count-index; i++)
    {
        data[index] = alphas[i];
        combinationUtil(alphas, data, i+1, end, index+1, count);
    }
}

// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
void printCombination(char alphas[], int n, int count)
{
    int data[count+1];
    combinationUtil(alphas, data, 0, n-1, 0, count);
}

int main()
{
    fp = fopen ("C:\Users\vidit\\Documents\\CODE\\CODE\\C++\\wrds.txt","w");
    char alphas[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Provide here the characters which you wants to use
    int i;
    int len = strlen(alphas);
    for(i = 0; i<len; i++)
        printCombination(alphas, len, i+1);
    fclose (fp);
    return 0;
}

解决方案和解释都会非常有帮助。 控制台输出将需要很长时间。

1 个答案:

答案 0 :(得分:0)

看看这段代码

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

您可以将控制台重定向到文件:)