標籤: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;