C 如何从递归函数内部写入文件

C 如何从递归函数内部写入文件,c,file-io,C,File Io,在这里编程。请检查下面的代码。。。这是一个给定词汇表的蛮力组合生成器。它不是编译。你能指出错误吗?如果可能,请告诉我在这种情况下如何为文件和终端输出编写单独的函数。谢谢你的时间 #include <stdio.h> #include <string.h> #include <stdlib.h> static const char alphabet[] = "abcd";//vocabulary static const int alphabetSize = s

在这里编程。请检查下面的代码。。。这是一个给定词汇表的蛮力组合生成器。它不是编译。你能指出错误吗?如果可能,请告诉我在这种情况下如何为文件和终端输出编写单独的函数。谢谢你的时间

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static const char alphabet[] = "abcd";//vocabulary
static const int alphabetSize = sizeof(alphabet) - 1;
void bruteImpl(char* str, int index, int maxDepth)//main recursive function
{
    for (int i = 0; i < alphabetSize; ++i)
    {
        str[index] = alphabet[i];
        if (index == maxDepth - 1) 
        {
            printf("%s\n", str);
            fprintf(fp, "%s\n", str);// error 
        }
        else bruteImpl(str, index + 1, maxDepth);
    }
}
void bruteSequential(int maxLen)
{
    char* buf = malloc(maxLen + 1);
    for (int i = 1; i <= maxLen; ++i)
    {
        memset(buf, 0, maxLen + 1);
        bruteImpl(buf, 0, i);
    }
    free(buf);
}
int main(void)
{
    FILE *fp;//warning
    fp = fopen("output", "w");//warning

    bruteSequential(5);
    return 0;
}
#包括
#包括
#包括
静态常量字符字母[]=“abcd”//词汇
静态常量int alphabetize=sizeof(alphabet)-1;
void bruteImpl(char*str,int-index,int-maxDepth)//主递归函数
{
for(int i=0;i对于注释中提到的(int i=1;i。为了在递归函数中使用文件流,必须将开放流作为参数传递给每个函数。只需在每个函数声明中包含
file*name
作为参数,即可使输出文件对函数可用

除了
FILE*
参数外,不需要将
alphabet
alphabetize
声明为
static
。这两个值都已通过
FILE
范围和持续时间声明为
global
变量


由于不知道您的代码的意图,很难确定
我是否会显示您所显示的代码片段的确切错误消息。您为什么不尝试使用编译器编译它?如果您有特定的问题,请询问它。甚至不必在程序内进行文件i/O。只需编写到stdout并让shell运行即可andle重定向。不要认为文件输出在某种程度上不同于终端输出。您的问题(文件I/O和递归)是您没有将输出文件流传递给递归函数,因此它不知道您所说的
fp
。或者(消除这种想法)将
FILE*fp;
设置为全局变量或将其作为额外参数传递给函数。在使用该文件之前,请务必检查是否已成功打开该文件。这样就可以了。非常感谢!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

const char alphabet[] = "abcd";            /* no need for 'static' already file scope */
const int alphabetSize = sizeof(alphabet) - 1;

void bruteImpl(char* str, int index, int maxDepth, FILE *fptr)  /* pass FILE * as arg */
{
    for (int i = 0; i < alphabetSize; ++i)
    {
        str[index] = alphabet[i];
        if (index == maxDepth - 1) 
        {
            printf("%s\n", str);
            fprintf(fptr, "%s\n", str);
        }
        else bruteImpl(str, index + 1, maxDepth, fptr);
    }
}

void bruteSequential(int maxLen, FILE *fptr)                    /* pass FILE * as arg */
{
    char* buf = malloc(maxLen + 1);
    for (int i = 1; i < maxLen; ++i)           /* check < maxLen instead of <= maxLen */
    {
        memset(buf, 0, maxLen + 1);
        bruteImpl(buf, 0, i, fptr);
    }
    free(buf);
}

int main(void)
{
    FILE *fp;
    fp = fopen("output", "w");
    /* you should validate fp is not NULL here */

    bruteSequential (alphabetSize + 1, fp);     /* pass alphabetSize + 1 & fp as args   */
    return 0;
}
$ ./bin/bseq
a
b
c
d
aa
ab
ac
ad
...
dd
aaa
aab
...
ddd
aaaa
...
dddd