Linux編程實踐——檔案操作裡神秘的當前指標

來源:互聯網
上載者:User

在《Unix\Linux編程實踐教程》 一書第56頁有一段話:

Unix每次開啟一個檔案都會儲存一個指標來記錄檔案的當前位置,示

read從當前位置讀入指定長度的資料,

然後移動當前位置指標,

指向下一個未讀的資料

當從檔案讀資料時,核心從指標所標明的地方開始,

讀取指定的位元組,然後移動位置指標,

指向下一個未被讀取的位元組,寫檔案的操作也是類似的。

指標是與檔案描述符相關聯的,而不是與檔案關聯,

所以如果兩個程式同時開啟一個檔案,這時會有兩個指標,

兩個程式對檔案的讀操作不會互相干擾。

 

要接開檔案當前指標的面紗,定位它,有個方法:

使用off_t oldpos = lseek(int fd,off_t dist, int base)函數可以返回當前位置——lseek(fd, 0, SEEK_CUR),SEEK_CUR這個參數標明,在當前指標的位置做零位移,所以返回的同樣是當前指標位置。

借書中的例子結合這個函數,查看檔案開啟時當前指標的移動動向:

#include <stdio.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
struct utmp current_record;
int utmpfd,currfd;//檔案描述符,當前指標
int reclen =sizeof(current_record);
if((utmpfd=open(UTMP_FILE, O_RDONLY)) ==-1){
perror(UTMP_FILE);
exit(1);
}
currfd = lseek(utmpfd,0, SEEK_CUR);
printf(">utmpfd=%d,currfd=%d,sizeof(utmp)=%d\n",utmpfd,currfd,sizeof(struct utmp));
while(read(utmpfd, &current_record, reclen) == reclen)
{
currfd = lseek(utmpfd,0, SEEK_CUR);
printf(">utmpfd=%d,currfd=%d\n",utmpfd,currfd);
show_info(&current_record);
}
close(utmpfd);
return0;
}
show_info( struct utmp *utbufp )
{
printf("%-8.8s", utbufp->ut_name); /* the logname */
printf(""); /* a space */
printf("%-8.8s", utbufp->ut_line); /* the tty */
printf(""); /* a space */
printf("%10ld", utbufp->ut_time); /* login time */
printf(""); /* a space */
#ifdef SHOWHOST
printf("(%s)", utbufp->ut_host); /* the host */
#endif
printf("\n"); /* newline */
}

這段代碼,原是讀取utmp檔案,該檔案記錄了使用者登入詳細資料,逐條讀取utmp結構體大小的資料(utmp結構體成員包含登入資訊),理論上來講,每次read大小為utmp結構體的資料後後,當前指標都應該後移utmp結構體大小,那麼查看一下結果是不是呢?

>utmpfd=3,currfd=0,sizeof(utmp)=384>utmpfd=3,currfd=384reboot   ~        1315959413 >utmpfd=3,currfd=768runlevel ~        1315959413 >utmpfd=3,currfd=1152LOGIN    tty4     1315959413 >utmpfd=3,currfd=1536LOGIN    tty5     1315959413 >utmpfd=3,currfd=1920LOGIN    tty2     1315959414 >utmpfd=3,currfd=2304LOGIN    tty3     1315959414 >utmpfd=3,currfd=2688lizh     tty6     1315979221 >utmpfd=3,currfd=3072lizh     tty1     1315959443 >utmpfd=3,currfd=3456lizh     pts/2    1315979126 >utmpfd=3,currfd=3840lizh     pts/3    1315979551 >utmpfd=3,currfd=4224lizh     pts/4    1316051702 

沒錯,每次read資料,當前指標currfd間隔正好是sizeof(struct utmp)。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.