开发者

c write the string to file line by line

fwrite don't work, what's wrong with my code?

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 does not do formatted output like that, you need fprintf:

fprintf (fp, "%d\n", tree->pop);

fwrite has the following prototype:

size_t fwrite (const void *restrict buff,
               size_t               sz,
               size_t               num,
               FILE *restrict       hndl);

and, since you're not even giving it that all-important fourth parameter (the file handle) in your call, it can pretty well whatever it pleases.

A decent compiler should have warned you about this.

You also have another problem here. Each time you call this function, you create the output file anew. That's not good for a recursive function since each recurring call will destroy the information already written.

You may want to open the file outside of the recursive function and simply use it within there.

Something like:

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜