简体   繁体   English

多次调用时 fwrite() 会覆盖吗?

[英]Does fwrite() overwrite when called multiple times?

Example: I am going through a tree and fwriting based on preorder traversal.示例:我正在遍历一棵树并根据前序遍历进行写作。

This is pseudocode:这是伪代码:

void func x ('','')
{
  do something 
  helper (char * filename, thing to be written);
}

void helper (char * filename, thing to be written)
{
  FILE * fp = fopen (filename,"w");
  fwrite(, , ,fp);
  fclose(fp);
  return 0;
}

Would it overwrite previous entries?它会覆盖以前的条目吗? If so, how can I prevent this?如果是这样,我该如何防止这种情况发生? Is there a better way to do this?有一个更好的方法吗?

As kaylum mentioned, the short answer is yes it does.正如 kaylum 所提到的,简短的回答是肯定的。

fopen with "w" will open the file at the beginning, so any writes will truncate and overwrite. fopen with "w" 将在开头打开文件,因此任何写入都将被截断并覆盖。 In order to avoid this, either reuse the file pointer returned by fopen every time, or use "a" in order to set fwrite to append mode.为了避免这种情况,要么重复使用 fopen 每次返回的文件指针,要么使用“a”将 fwrite 设置为 append 模式。

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

相关问题 C : 多次调用 fscanf 不起作用 - C : fscanf called multiple times does not work 为什么在单个printf中多次调用函数时,函数仅返回一个值? - Why does function return only one value when called multiple times in a single printf? 如何使用fwrite()多次写入默认结构值 - how to write default structure values multiple times using fwrite() 在C中多次调用时,字符串数组指针分段错误 - String array pointer segmentation fault when called multiple times in C 当文件是结构时,fwrite如何将数据复制到文件中 - how does fwrite copy data in a file when it's a structure fwrite 是如何工作的? - How does fwrite work? 如果在循环中多次调用了malloc()和realloc(),则free()会多次 - free()ing multiple times if malloc() and realloc() was called multiple times in a loop 当同一程序为同一操作两次调用ctime clock()时,为什么会给出不同的时间? - Why does ctime clock() give different times when called twice by same program for same operation? 为什么 realloc() 在多次调用时会在动态数组中引入一些随机值? - Why is realloc() introducing some random values into a dynamic array when called multiple times? 当我们使用斐波那契数列的递归方法调用 fib(6) 时, fib(3) 被调用了多少次? - How many times does fib(3) gets called when we call fib(6) using the recursive approach to Fibonacci series?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM