zoukankan      html  css  js  c++  java
  • Linux C ftruncate 函数清空文件注意事项(要使用 lseek 重置偏移量)

    转载:http://blog.csdn.net/a_ran/article/details/43562429

    int truncate(const char *path, off_t length);
    int ftruncate(int fd, off_t length);

    将文件大小改变为参数length指定的大小,如果原来的文件大小比参数length大,则超过的部分会被删除,如果原来的文件大小比参数length小,则文件将被扩展,

    与lseek系统调用类似,文件的扩展部分将以0填充。如果文件的大小被改变了,则文件的st_time 和st_ctime将会更新。

    If the file previously was larger than this size, the extra data is
    lost. If the file previously was shorter, it is extended, and the
    extended part reads as null bytes ('').

    The file offset is not changed.

    打开的文件清空,然后重新写入的需求,但是使用 ftruncate(fd, 0)后,并没有达到效果,反而文件头部有了'',长度比预想的大了。

    究其原因是没有使用 lseek 重置文件偏移量

    int fd;

    const char *s1 = "0123456789";
    const char *s2 = "abcde";

    fd = open("test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);

    write(fd, s1, strlen(s1));

    ftruncate(fd, 0);
    lseek(fd, 0, SEEK_SET);

    write(fd, s2, strlen(s2));

    close(fd);

    return 0;

    //先清空文件,再设置文件偏移量,否则会产生文件空洞

    ftruncate(fd, 0); 
    lseek(fd, 0, SEEK_SET); 

  • 相关阅读:
    <转>Logistic回归总结
    特征选择和降维的区别
    <转>SVM实现之SMO算法
    <转>KMP算法详解
    <转>主成分分析(Principal components analysis)-最大方差解释,最小平方差解释
    <转>与EM相关的两个算法-K-mean算法以及混合高斯模型
    <转>E-M算法
    隐马尔科夫
    机器学习之判别式模型和生成式模型
    复制图片
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/6323281.html
Copyright © 2011-2022 走看看