简体   繁体   English

c 将字符串逐行写入文件

[英]c write the string to file line by line

fwrite don't work, what's wrong with my code? 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 does not do formatted output like that, you need fprintf : fwrite不会像这样格式化 output ,你需要fprintf

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

fwrite has the following prototype: fwrite有以下原型:

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.每次调用此 function 时,都会重新创建 output 文件。 That's not good for a recursive function since each recurring call will destroy the information already written.这对于递归 function 来说并不好,因为每次重复调用都会破坏已经写入的信息。

You may want to open the file outside of the recursive function and simply use it within there.您可能希望在递归 function之外打开文件,然后在其中简单地使用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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