2014-11-09 32 views
-2

這裏編程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

請告訴我們你得到正是你展示的代碼片段的確切的錯誤消息。 – 2014-11-09 05:54:31

+0

爲什麼不嘗試使用編譯器進行編譯?如果您有特定的問題,請提問。 – eyalm 2014-11-09 05:54:52

+0

甚至不要在程序內部做文件I/O。只需寫入標準輸出並讓shell處理重定向。停止將文件輸出視爲與終端輸出不同。 – 2014-11-09 05:55:51

回答

0

正如評論中所述。爲了在遞歸函數中使用文件流,您必須將打開的流作爲參數傳遞給每個函數。只需將FILE *name作爲參數包含在每個函數聲明中,以使您的輸出文件可用於您的函數。

除了FILE *的論點之外,沒有必要聲明alphabetalphabetSizestatic。由於聲明爲global變量,所以這兩個值已被聲明爲file範圍和持續時間。

不知道您的代碼的意圖,很難確定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 
+0

這樣做。非常感謝! – 2014-11-09 08:32:59