[英]c write the string to file line by line
fwrite 不起作用,我的代碼有什么問題?
void printTree (struct recordNode* tree) {
char* report1;
FILE *fp = fopen("test.txt","w");
if (tree == NULL) {
return;
}
//if(fp) {
counter2++;
printTree(tree->right);
fwrite(fp,"%d\n", tree->pop);
//putc(tree->pop, fp);
//report1 = printf("%s = %d\n");
printTree(tree->left);
//}
fclose(fp);
}
fwrite
不會像這樣格式化 output ,你需要fprintf
:
fprintf (fp, "%d\n", tree->pop);
fwrite
有以下原型:
size_t fwrite (const void *restrict buff,
size_t sz,
size_t num,
FILE *restrict hndl);
而且,由於您甚至沒有在調用中為其提供最重要的第四個參數(文件句柄),因此它可以隨心所欲。
一個體面的編譯器應該會警告你這一點。
你這里還有另一個問題。 每次調用此 function 時,都會重新創建 output 文件。 這對於遞歸 function 來說並不好,因為每次重復調用都會破壞已經寫入的信息。
您可能希望在遞歸 function之外打開文件,然后在其中簡單地使用它。
就像是:
static void printTreeRecur (FILE *fp, struct recordNode* tree) {
if (tree == NULL) return;
printTreeRecur (fp, tree->right);
fprintf (fp, "%d\n", tree->pop);
printTreeRecur (fp, tree->left);
}
void printTree (struct recordNode* tree) {
FILE *fp = fopen ("test.txt", "w");
if (fp != NULL) {
printTreeRecur (fp, tree);
fclose(fp);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.