在“r +”模式下打开时,在C中清除/截断文件

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

/* 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 +”的语义是:

开放阅读和写作。 如果文件不存在,则创建该文件,否则将被截断。 流位于文件的开头。

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

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

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

如果您根本不需要再读取文件,那么“w”模式也可以。

你可以写一个像这样的函数:(伪代码)

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

这是满足您需求的最直接的解决方案。

请参阅:msdn.microsoft.com上的man truncate和_chsize_s

并包括必要的头文件。