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

时间:2014-11-09 05:52:19

标签: c file-io

在这里编程noob。请检查以下代码......这是一个针对特定词汇的强力组合生成器。它没有编译。你能指出错误(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;
}

1 个答案:

答案 0 :(得分:0)

如评论中所述。要在递归函数中使用文件流,必须将开放流作为参数传递给每个函数。只需在每个函数声明中包含FILE *name作为参数,以使输出文件可用于您的函数。

FILE *个参数外,无需将alphabetalphabetSize声明为static。由于声明为file变量,这两个值已经用global范围和持续时间声明。

不知道代码的意图,很难确定i <= maxLen是否应该是i < maxLen。我怀疑是,但检查。

考虑到这些因素,您的代码可以按如下方式实现。在main()中注意,bruteSequential (alphabetSize + 1, fp);也已更改,以删除5的硬编码值。您将alphabetSize声明为全局 - 使用它。如果您有任何其他问题,请与我们联系。

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

输出(在./output中):

$ ./bin/bseq
a
b
c
d
aa
ab
ac
ad
...
dd
aaa
aab
...
ddd
aaaa
...
dddd