当已在"r +"中打开文件时,清除/截断C中的文件.模式

编程入门 行业动态 更新时间:2024-10-27 08:35:12
本文介绍了当已在"r +"中打开文件时,清除/截断C中的文件.模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的代码当前看起来像这样(这些步骤分为多个功能):

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

我知道我可以在"w"模式下打开文件,但是在这种情况下,我不想这样做.我知道unistd.h/sys/types.h中有一个功能ftruncate,但是我不想使用这些功能,我的代码应该具有很高的可移植性(在Windows上也是如此).

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?

推荐答案

使用标准C,唯一的方法是每次需要截断时都以"w +"模式重新打开文件.您可以为此使用freopen(). "w +"将继续允许对其进行读取,因此无需在"r +"模式下再次关闭并重新打开. "w +"的语义是:

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.

(摘自fopen(3)手册页.)

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

使用freopen()时,您可以将NULL指针作为文件名参数传递:

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

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

如果您根本不再需要读取文件,则在"w"模式下也可以.

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

更多推荐

当已在"r +"中打开文件时,清除/截断C中的文件.模式

本文发布于:2023-10-08 14:00:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472840.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   已在   模式   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!