天天看點

linux系統調用 ftruncate設定檔案大小

  • 頭檔案:​

    ​<unistd.h> <sys/types.h>​

  • 函數使用:

    ​​

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

    ​​

    ​int ftruncate(int fd, off_t length);​

  • 函數參數:

    可以看到兩者有不同的使用方式,​​

    ​truncate​

    ​​是通過檔案路徑來裁剪檔案大小,而​

    ​ftruncate​

    ​是通過檔案描述符進行裁剪;
  • 傳回值

    成功:0

    失敗:-1

  • 權限要求:

    ​​

    ​ftruncate​

    ​​要求檔案被打開且擁有可寫權限

    ​​

    ​truncate​

    ​要求檔案擁有可寫權限
  • 注意:

    如果要裁剪的檔案大小大于設定的​​

    ​off_t length​

    ​​,檔案大于length的資料會被裁剪掉

    如果要裁剪的檔案小于設定的​​

    ​offt_t length​

    ​​,則會進行檔案的擴充,并且将擴充的部分都設定為​

    ​\0​

    ​​,檔案的偏移位址不會發生變化

    ​​

    ​ftruncate​

    ​主要被用作POSIX共享記憶體對象的大小設定
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define TRUN "./test_truncate"
int main() {
  char *name = "test_file";
  //打開檔案且擁有可寫權限
  int fd = open(name,O_CREAT|O_RDWR,0666);
  if ( -1 == fd ) {
    printf("open %s failed \n",name);
    _exit(-1);
  }
  
  //通過檔案描述符對檔案大小進行裁剪
  if(ftruncate(fd,4096) != -1) {
    printf("ftruncate success \n");
  }
  
  //直接設定指定路徑的檔案大小
  if(truncate(TRUN,8192) != -1) {
    printf("truncate success\n");
  }

  //通過fstat擷取檔案屬性資訊
  struct stat buf;
  fstat(fd,&buf);
  printf("stat.size is %ld \n",buf.st_size);
  printf("stat.inode is %ld \n",buf.st_ino);
  printf("stat.mode is %lo(octal) \n",(unsigned long)buf.st_mode);
  printf("stat.bytes is %ld \n",buf.st_blksize);
  close(fd);
  return 0;
}