今天用 ftruncate 截断文件, 但怎么都不能达到预料的效果, 截断后文件中的内容比较杂, 而且文件大小也保持原来的.
添加 fflush() 和 rewind() 后OK.
以下是测试代码:
#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { FILE *fp; char *file = "tmp"; int i; int fd; fp = fopen(file, "w"); if(fp == NULL) { printf("fopen failed\n"); return -1; } for(i=0; i<1000; i++) { fprintf(fp, "%d -- abcedfg \n", i); } fflush(fp); fd = fileno(fp); if(ftruncate(fd, 0)<0) { perror(""); return -1; } rewind(fp); fprintf(fp, "end\n"); fclose(fp); return 0; }
程序运行后, tmp 文件的内容为 end , 大小为4字节.
- - - - - - - - - -
在调用 ftruncate() 前用 rewind() 也行.
但用 ftruncate()截断过的文件, 在用 fread, fwrite拷贝到另外一个文件时, 会出现乱码和一些'\0'字符. 改用 fgets 和 fputs 则正常.