您的位置:首页 > 其它

c 中使用 ftruncate() 前需要 fflush(), 使用后需要 rewind()

2016-07-12 08:40 232 查看
今天用 ftruncate 截断文件, 但怎么都不能达到预料的效果, 截断后文件中的内容比较杂, 而且文件大小也保持原来的.

添加 fflush() 和 rewind() 后OK.

以下是测试代码:

[cpp]
view plain
copy

#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 则正常.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: