C 庫函數 - fgetpos()
描述
C 庫函數 int fgetpos(FILE *stream, fpos_t *pos) 獲取流 stream 的當前檔位置,並把它寫入到 pos。
聲明
下麵是 fgetpos() 函數的聲明。
int fgetpos(FILE *stream, fpos_t *pos)
參數
- stream -- 這是指向 FILE 對象的指針,該 FILE 對象標識了流。
- pos -- 這是指向 fpos_t 對象的指針。
返回值
如果成功,該函數返回零。如果發生錯誤,則返回非零值。
實例
下麵的實例演示了 fgetpos() 函數的用法。
#include <stdio.h> int main () { FILE *fp; fpos_t position; fp = fopen("file.txt","w+"); fgetpos(fp, &position); fputs("Hello, World!", fp); fsetpos(fp, &position); fputs("這將覆蓋之前的內容", fp); fclose(fp); return(0); }
讓我們編譯並運行上面的程式,這將創建一個檔 file.txt,它的內容如下。首先我們使用 fgetpos() 函數獲取檔的初始位置,接著我們向檔寫入 Hello, World!,然後我們使用 fsetpos() 函數來重置寫指針到檔的開頭,重寫檔為下列內容:
這將覆蓋之前的內容
現在讓我們使用下麵的程式查看上面檔的內容:
#include <stdio.h> int main () { FILE *fp; int c; int n = 0; fp = fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); }