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

标签 c fopen truncate c89

我的代码目前看起来像这样(这些步骤分成多个函数):

/* 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 上也是如此)。

是否可以在不关闭/重新打开文件的情况下清除文件?

最佳答案

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

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) 手册页。)

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

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

如果您根本不需要再从文件中读取,when "w"模式也可以。

关于当已经以 "r+"模式打开时,在 C 中清除/截断文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12981018/

相关文章:

C程序自动四舍五入

c - gcc make 进程在做什么?

php - 使用 fopen()、fgets() 和 PHP 的流式 JSON 解析器

PHP 无法读取包含 PHP 代码的文件作为文本文件

java - java中的html截断器

css - overflow hidden

c - 如何使用 ASSERT 检查字符串是否包含字符?

c - fopen 创建文件 : Access modes Conversion

sql - 截断模式中的脚本表不起作用

c - printf中的 "%.6d"是什么意思