_风雨晴 2017-06-18 06:43 采纳率: 0%
浏览 1752

关于linux中truncate函数的问题。

为什么我使用ftruncate截断文件后文件大小确实改变了,但是用read读取文件的内容还是截断之前的呢?

 int main(void)
{
    //创建文件
    int new_fd = open("file/a",O_RDWR|O_CREAT|O_EXCL,0644);
    if(-1==new_fd)
    {
        printf("%d: ",__LINE__-3);
        perror("creat");
        exit(-1);
    }
    //打开文件
    int old_fd = open("file/file_test",O_RDWR);
    if(-1==old_fd)
    {
        printf("%d: ",__LINE__-3);
        perror("open");
        exit(-1);
    }
    //复制文件
    char buff[1024];
    while(read(old_fd,buff,sizeof(buff)))
    {
        int res = write(new_fd,buff,strlen(buff));
        if(-1==res)
        {
            printf("%d: ",__LINE__-3);
            perror("write");
            close(new_fd);
            close(old_fd);
            exit(-1);
        }
        memset(buff,sizeof(buff),0);
    }
    memset(buff,sizeof(buff),0);
    close(old_fd);

    //读出修改后的文件
    lseek(new_fd,0,SEEK_SET);
    while(read(new_fd,buff,sizeof(buff)))
    {   
        printf("%s",buff);
        memset(buff,sizeof(buff),0);
    }
    printf("\n\n");
    //获得修改过后的文件的信息
    struct stat st;
    if(-1==fstat(new_fd,&st))
    {
        printf("%d: ",__LINE__-3);
        perror("stat");
        close(new_fd);
        exit(-1);
    }
    printf("文件大小为%d\n",st.st_size);
    printf("文件最后修改时间为%s",ctime(&st.st_mtime));
    printf("文件权限为%o\n\n",st.st_mode&0777);
    //截取前100个字节
    if(-1==ftruncate(new_fd,100))
    {
        printf("%d: ",__LINE__-3);
        perror("truncate");
        close(new_fd);
        exit(-1);
    }

    close(new_fd);   //先关闭文件描述符
    new_fd = open("file/a",O_RDWR);//再次打开
    if(-1==new_fd)
    {
        printf("%d: ",__LINE__-3);
        perror("creat");
        exit(-1);
    }

#ifdef DE
    if(-1==fstat(new_fd,&st))
    {
        printf("%d: ",__LINE__-3);
        perror("stat");
        close(new_fd);
        exit(-1);
    }
    printf("文件大小为%d\n",st.st_size);
    printf("文件最后修改时间为%s",ctime(&st.st_mtime));
    printf("文件权限为%o\n\n",st.st_mode&0777);
#endif
    //读出文件
    memset(buff,sizeof(buff),0);
    lseek(new_fd,0,SEEK_SET);
    while(read(new_fd,buff,sizeof(buff)))
    {   
        printf("%s",buff);
        memset(buff,sizeof(buff),0);
    }
    printf("\n\n");
    //改变新建文件的权限

    close(new_fd);
    remove("file/4_file");
    return 0;
}

  • 写回答

1条回答 默认 最新

  • devmiao 2017-06-18 08:39
    关注
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮