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 ('\0').

The file offset is not changed.

 

打開的文件清空,然后重新寫入的需求,但是使用 ftruncate(fd, 0)后,並沒有達到效果,反而文件頭部有了'\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); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM