Linux-Function-truncate;

來源:互聯網
上載者:User

標籤:io   ar   os   for   on   檔案   資料   art   cti   

#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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.