我的代码目前看起来像这样(这些步骤分成多个函数):
/* 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/