首页 > 代码库 > Linux-Function-truncate;

Linux-Function-truncate;

#include <unistd.h>

#include <sys/types>

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

int ftruncate(int fd,off_t length);

The truncate and ftruncate function cause the regular file named by path or referenced by fd to be truncated to a size of precisely

length bytes.

/*truncate 和 ftruncate函数由参数path命名或者由参数fd指向的有规律的文件截取到参数length指定大小的字节*/

If the file previously was larger then this size , the extra data is lost . If the file previously was shorter , it is extended, and the extended

part reads as null bytes(‘\0‘).

/*如果原文件比指定大小要大,则超出的数据会丢失。如果原文件如果小些,则将被扩大,扩大的部分读取为空字符*/

The file offset is not changed.

/*文件指针不会改变*/

If the size changed , then the st_ctime and st_time fields for the file are update ,and the set-usr-ID and set-group-ID permission bits may

be cleared.

/*如果大小改变,文件的st_ctime和st_time成员将更新,set-usr-ID和set-group-ID位可能被清除*/

On success zero is returned , On error -1 is returned and errno is set appropriately.

/*成功返回0。失败返回-1并且设置适当的错误号errno*/

With ftruncate(), the file must be open for writing; with truncate. the file must be writable.

/*要可写,文件的open模式必须包含写标记*/

Simple example:

int main()

{

  struct stat st;

  int fd = open("b.txt",O_CREAT|O_RDWR);

  //或者O_WRONLY,此时新文件大小为0

  ftruncate(fd,10);

  //将文件扩展为十个字节

  /*此处可以添加写入代码*/

  fstat(fd,&st);

  printf("Size of file is %d", st.st_size);

  close(fd);

  truncate("b.txt",5);

  //将文件截取为5个字节大小,多余的5个字节将被舍弃

  stat("b.txt",&st);

  printf("Size of file is %d", st.st_size);

  return 0;

}

Linux-Function-truncate;