Linux 文件截斷的幾種方式


文件截斷, 指的是將文件內容分成兩半, 只保留需要的文件長度的那部分. 通常, 將文件長度截斷為0.
文件截斷方式:
1. 使用系統調用open/fopen O_TRUNC截斷
open截斷文件, 會清空文件已有內容, 即保留長度為0. 指定O_TRUNC標識時, 文件必須可寫方式(如O_RDWR, O_WRONLY)打開.

例子,

int fd = open(FILE_PATH, O_RDWR | O_TRUNC); 

close(fd);

注意: 如果fd指向FIFO文件, 或終端設備文件, O_TRUNC標識將會忽略

類似地, 可以使用C庫函數fopen截斷文件, 功能類似於open, 接口形式不一樣
例子,

// "w" <=> O_WRONLY | O_CREAT | O_TRUNC
// "w+" <=> O_RDWR | O_CREAT | O_TRUNC
FILE* fp = fopen(FILE_PATH, "w"); // "w+" 也可以

fclose(fp);

2. 使用系統調用truncate/ftruncate
truncate可以將文件截斷為指定長度(byte).
同樣可以使用ftruncate, 區別是參數類型, truncate接受字符串形式文件路徑, ftruncate接受已打開的文件描述符作為文件路徑.

#include <unistd.h>
#include <sys/types.h>

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

例子,

int ret = truncate(FILE_PATH, 0); // 文件長度截斷為0
ret = truncate(FILE_PATH2, 100); // 文件長度截斷為100byte

3. 使用shell命令truncate
-s 選項是截斷為指定byte長度

$ vim testfile
abcd
$ truncate ./testfile -s 2
$ cat testfile
ab


免責聲明!

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



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