简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM