先看一段完整代碼:
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <error.h>
#include <stdlib.h>
/* 自定義錯誤處理函數 */
void my_err(const char *err_string, int line)
{
fprintf(stderr, "line:%d ", line);
perror(err_string);
exit(1);
}
/* 自定義讀數據函數 */
int my_read(int fd)
{
int len, ret, i;
char read_buf[64];
/* 先移動到尾部,再取當前偏移,得到文件長度 */
if (lseek(fd, 0, SEEK_END) == -1) my_err("lseek", __LINE__);
if ((len = lseek(fd, 0, SEEK_CUR)) == -1) my_err("lseek", __LINE__);
if (lseek(fd, 0, SEEK_SET) == -1) my_err("lseek", __LINE__);
printf("len:%d\n", len);
if ((ret = read(fd, read_buf, len)) == -1) my_err("read", __LINE__);
for (i = 0; i < len; i++) printf("%c", read_buf[i]);
printf("\n");
return ret;
}
int main()
{
int fd;
char write_buf[32] = "hellow world";
if ((fd = open("example_63.c", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) == -1)
my_err("open", __LINE__);
else
printf("creat file success\n");
if (write(fd, write_buf, strlen(write_buf)) != strlen(write_buf))
my_err("write", __LINE__);
my_read(fd);
printf("/*-------------------------*/\n");
if (lseek(fd, 10, SEEK_END) == -1) my_err("lseek", __LINE__);
my_read(fd);
close(fd);
return 0;
}
代碼裡有兩個自定義子函數。第一個 my_err 用於統一錯誤處理,核心調用 perror()。它的英文說明是:The perror() function produces a message on standard error describing the last error encountered during a call to a system or library function——也就是把上一次系統或庫函數調用失敗的錯誤描述打印出來,先輸出括號裡的自定義字符串,再附上具體錯誤內容。
第二個 my_read 負責讀取數據,其中 __LINE__ 參數會帶出當前行號,一旦出錯就能迅速定位到具體代碼行,調試時非常省事。
另外幾個要點:O_TRUNC 表示文件存在時清空內容,S_IRWXU 設置的是用戶對該文件的操作權限;第二次讀之前把偏移移到「尾部往前 10 字節」,正好用來對比兩次讀取結果的差異。關於代碼的細節解釋都放在註釋中了。