如果您想将文件的先前内容保留到一定长度(大于零的长度,其他答案提供了),则 POSIX 提供truncate() http://pubs.opengroup.org/onlinepubs/9699919799/functions/truncate.html and ftruncate() http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html工作的职能。
#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);
该名称表明了主要目的 - 缩短文件。但是,如果指定的长度比先前的长度长,则文件将增长(零填充)到新的大小。注意ftruncate()
适用于文件描述符,而不是FILE *
;你可以使用:
if (ftruncate(fileno(fp), new_length) != 0) ...error handling...
但是,您应该注意混合文件流(FILE *
)和文件描述符(int
)访问单个文件很容易导致混乱——请参阅某些问题的评论。这应该是最后的手段。
不过,出于您的目的,打开时截断可能就是您所需要的,为此,其他人提供的选项就足够了。
对于 Windows,有一个函数SetEndOfFile() https://msdn.microsoft.com/en-us/library/windows/desktop/aa365531(v=vs.85).aspx和一个相关的函数SetFileValidData() https://msdn.microsoft.com/en-us/library/windows/desktop/aa365544(v=vs.85).aspx可以完成类似工作但使用不同接口的函数。基本上,您寻找要设置文件结尾的位置,然后调用该函数。
还有一个功能_chsize()
如记录在answer https://stackoverflow.com/a/874704/15168 by sofr https://stackoverflow.com/users/103521/sofr.