clear/truncate file in C when already open in “r+” mode

自古美人都是妖i 提交于 2019-12-19 19:48:09

问题


My code currently looks something like this (these steps splitted into multiple functions):

/* open file */
FILE *file = fopen(filename, "r+");

if(!file) {

  /* read the file */

  /* modify the data */

  /* truncate file (how does this work?)*/

  /* write new data into file */

  /* close file */
  fclose(file);
}

I know I could open the file with in "w" mode, but I don't want to do this in this case. I know there is a function ftruncate in unistd.h/sys/types.h, but I don't want to use these functions my code should be highly portable (on windows too).

Is there a possibility to clear a file without closing/reopen it?


回答1:


With standard C, the only way is to reopen the file in "w+" mode every time you need to truncate. You can use freopen() for this. "w+" will continue to allow reading from it, so there's no need to close and reopen yet again in "r+" mode. The semantics of "w+" are:

Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

(Taken from the fopen(3) man page.)

You can pass a NULL pointer as the filename parameter when using freopen():

my_file = freopen(NULL, "w+", my_file);

If you don't need to read from the file anymore at all, when "w" mode will also do just fine.




回答2:


You can write a function something like this:(pseudo code)

if(this is linux box) 
use truncate()
else if (this is windows box)
use _chsize_s()

This is the most straightforward solution for your requirement.

Refer: man truncate and _chsize_s at msdn.microsoft.com

and include necessary header files too.



来源:https://stackoverflow.com/questions/12981018/clear-truncate-file-in-c-when-already-open-in-r-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!