我的代码目前长这样(这些步骤被拆分成多个函数):
/* 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)。
有没有可能在不关闭/重新打开文件的情况下清除文件?
rewind(file); fopen(filename, "w");
。而且我仍然可以使用文件指针file
!如果您能将此嵌入到您的答案中,那就太好了。 - MarcDefiantfreopen()
而不是fopen()
。如果你只是再次使用fopen()
,你会泄漏旧的 FILE(类似于使用malloc()
分配内存但没有使用free()
释放它)。这也更容易,因为如果你已经有一个打开的 FILE 句柄,你不需要传递文件名。 - Nikos C.