繁体   English   中英

c 将字符串逐行写入文件

[英]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.

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